package cn.com.nes.site.service.workOrder.impl;

import cn.com.nes.common.annotation.CallCenterTransactional;
import cn.com.nes.common.em.*;
import cn.com.nes.common.em.platform.CallMethodEnum;
import cn.com.nes.common.exception.BusinessException;
import cn.com.nes.common.exception.IllegalBusinessException;
import cn.com.nes.common.exception.MissBusinessParameterException;
import cn.com.nes.common.util.MathUtils;
import cn.com.nes.common.util.XzqhUtils;
import cn.com.nes.common.web.CommonResult;
import cn.com.nes.mybatis.agent.ope.entity.IsEquipmentInfo;
import cn.com.nes.mybatis.agent.ope.entity.IsInstallInfo;
import cn.com.nes.mybatis.agent.ope.mapper.IsSparePartMapper;
import cn.com.nes.mybatis.agent.ope.mapper.QueryCustomerEquipmentMapper;
import cn.com.nes.mybatis.agent.project.entity.TProject;
import cn.com.nes.mybatis.agent.system.entity.*;
import cn.com.nes.mybatis.agent.system.mapper.BindCompanyMapper;
import cn.com.nes.mybatis.agent.system.mapper.TUserMapper;
import cn.com.nes.mybatis.callcenter.entity.CcCompany;
import cn.com.nes.mybatis.callcenter.entity.CcUser;
import cn.com.nes.mybatis.callcenter.entity.WorkOrderInfo;
import cn.com.nes.mybatis.callcenter.entity.WorkOrderRecord;
import cn.com.nes.mybatis.callcenter.mapper.*;
import cn.com.nes.site.entity.PageData;
import cn.com.nes.site.entity.bo.crm.BatchSaveCrmFlowDataBO;
import cn.com.nes.site.entity.bo.crm.CrmFlowTableRelationshipBO;
import cn.com.nes.site.entity.bo.workorder.*;
import cn.com.nes.site.entity.dto.product.GGoodsDTO;
import cn.com.nes.site.entity.dto.workOrder.*;
import cn.com.nes.site.entity.em.*;
import cn.com.nes.site.entity.em.company.CompanyIdEnum;
import cn.com.nes.site.entity.em.workOrder.CancelWorkOrdersStatusEnum;
import cn.com.nes.site.entity.vo.NullVO;
import cn.com.nes.site.entity.vo.project.ProjectAcceptanceVO;
import cn.com.nes.site.entity.vo.project.WorkOrderReviewVo;
import cn.com.nes.site.entity.vo.workOrder.*;
import cn.com.nes.site.handle.SendMessageHandler;
import cn.com.nes.site.service.crm.customer.CrmCustomerService;
import cn.com.nes.site.service.crm.customer.CustomerHouseService;
import cn.com.nes.site.service.crm.customer.CustomerStaffService;
import cn.com.nes.site.service.crm.customer.dto.CustomerDTO;
import cn.com.nes.site.service.crm.customer.dto.CustomerHouseDTO;
import cn.com.nes.site.service.crm.customer.dto.CustomerStaffDTO;
import cn.com.nes.site.service.crm.flow.CrmFlowTableRelationshipService;
import cn.com.nes.site.service.crm.opportunity.CrmOpportunityService;
import cn.com.nes.site.service.crm.opportunity.dto.OpportunityInfoDto;
import cn.com.nes.site.service.crm.order.SaleOrderInfoService;
import cn.com.nes.site.service.crm.order.SalePriceService;
import cn.com.nes.site.service.crm.order.bo.CancelSaleOrderBO;
import cn.com.nes.site.service.crm.order.dto.SaleOrderInfoDTO;
import cn.com.nes.site.service.crm.order.dto.SalePriceMasterDTO;
import cn.com.nes.site.service.monitor.EquipmentService;
import cn.com.nes.site.service.monitor.IsInstallInfoService;
import cn.com.nes.site.service.monitor.dto.EquipmentInfoDTO;
import cn.com.nes.site.service.product.GGoodsService;
import cn.com.nes.site.service.project.ProjectServiceUserAuthService;
import cn.com.nes.site.service.project.TProjectService;
import cn.com.nes.site.service.project.dto.TProjectDTO;
import cn.com.nes.site.service.system.callCenter.CallCenterService;
import cn.com.nes.site.service.system.company.BusinessCompanyService;
import cn.com.nes.site.service.system.company.CcCompanyService;
import cn.com.nes.site.service.system.dict.TParamService;
import cn.com.nes.site.service.system.region.XzqhService;
import cn.com.nes.site.service.system.region.dto.XzqhDTO;
import cn.com.nes.site.service.system.user.CcUserService;
import cn.com.nes.site.service.system.user.SystemUserService;
import cn.com.nes.site.service.workOrder.*;
import cn.com.nes.site.service.workOrder.bo.*;
import cn.com.nes.site.service.workOrder.dto.*;
import cn.com.nes.site.service.workOrder.dto.callCenter.WorkOrderRecordListDto;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 工单业务实现
 * 补充说明：自2024-08-20起，work_order_info表的project_id作废，以crm_flow_table_relationship表为准
 */
@Slf4j
@Service
public class WorkOrderServiceImpl extends ServiceImpl<CallWorkOrderInfoMapper, WorkOrderInfo> implements WorkOrderService {

    @Resource
    private CallCenterService callCenterService;
    @Resource
    private WorkOrderRepairPicService workOrderRepairPicService;
    @Resource
    private WorkOrderDataMapper workOrderDataMapper;
    @Resource
    private WorkOrderServiceStrategyFactory workOrderServiceStrategyFactory;
    @Resource
    private SaleOrderInfoService saleOrderInfoService;
    @Resource
    private SalePriceService salePriceService;
    @Resource
    private IsSparePartMapper sparePartMapper;
    @Resource
    private CallWorkOrderInfoService callWorkOrderInfoService;
    @Resource
    private CallWorkOrderPicService callWorkOrderPicService;
    @Resource
    private WorkOrderRecordMapper workOrderRecordMapper;
    @Resource
    private CcUserService ccUserService;
    @Resource
    private BusinessCompanyService businessCompanyService;
    @Resource
    private CcCompanyService ccCompanyService;
    @Resource
    private CustomerStaffService customerStaffService;
    @Resource
    private CrmCustomerService crmCustomerService;
    @Resource
    private CustomerHouseService customerHouseService;
    @Resource
    private GGoodsService gGoodsService;
    @Resource
    private TParamService tParamService;
    @Resource
    private XzqhService xzqhService;
    @Resource
    private EquipmentService equipmentService;
    @Resource
    private SystemUserService systemUserService;
    @Resource
    private IsInstallInfoService isInstallInfoService;
    @Resource
    private ProjectServiceUserAuthService projectServiceUserAuthService;
    @Resource
    private TProjectService tProjectService;
    @Resource
    private ParamParamMapper paramParamMapper;
    @Resource
    private CrmFlowTableRelationshipService crmFlowTableRelationshipService;
    @Resource
    private WorkOrderRejectionInfoService workOrderRejectionInfoService;
    @Resource
    private QueryCustomerEquipmentMapper queryCustomerEquipmentMapper;
    @Resource
    private WorkOrderRecordService workOrderRecordService;
    @Resource
    private TUserMapper tUserMapper;
    @Resource
    private BindCompanyMapper bindCompanyMapper;
    @Resource
    private TXzqhMapper tXzqhMapper;
    @Resource
    private CrmOpportunityService crmOpportunityService;
    @Resource
    private AgentPushCtceService agentPushCtceService;
    @Resource
    private WorkOrderCancelRecordService workOrderCancelRecordService;
    @Resource
    private SendMessageHandler sendMessageHandler;

//    // 常量
//    private final String accessKeyId = "LTAI4GGGPjJdh83sy2vf2Hx3";
//    private final String endpoint = "https://oss-cn-beijing.aliyuncs.com";
//
//    private final String accessKeySecret = "LsuL7otABT1a6eIXdhH7dOWcqGeqos";
//    private final String bucketName = "nescallcenter";

    /**
     * 单条派发安装工单
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public String distributeWorkOrderInstall(DistributeWorkOrderInstallBO bo) throws Exception {
        // 查询销售订单详情
        SaleOrderInfoDTO saleOrderDetail = saleOrderInfoService.getOrderDetatil(bo.getSaleOrderId());
        // 校验入参
        validateInstallUserAuth(bo, saleOrderDetail.getAreaCode());
        // 查询客户详情
        CustomerDTO customerDetail = crmCustomerService.getCustomerById(bo.getCustomerId());
        // 查询系统单详情
        SalePriceMasterDTO priceMasterDetail = salePriceService.getPriceSheetDetail(bo.getPriceMasterId());
        if (StrUtil.isBlank(priceMasterDetail.getBuildId())) {
            throw new IllegalBusinessException("当前选定的系统单未绑定房屋信息,派单失败!");
        }

        // 查询经纬度
        Map<String, BigDecimal> coordinate = xzqhService.getCoordinate(saleOrderDetail.getAreaCode());
        // 处理安装人员id - 安装人id转换成长效管护安装人id
        TUser installUserInfo = systemUserService.getUserInfoByUserId(bo.getMaintainId());
        if (ObjectUtil.isNull(installUserInfo) || ObjectUtil.isNull(installUserInfo.getCallCenterUserId())) {
            throw new IllegalBusinessException("转换安装人id异常,安装人信息:" + JSON.toJSONString(installUserInfo));
        }
        // 组装参数workTypeId
        SaveWorkOrderBO saveWorkOrderBo = new SaveWorkOrderBO();
        saveWorkOrderBo.setUserInfo(bo.getUserInfo());
        saveWorkOrderBo.setSaleOrderId(bo.getSaleOrderId());
        saveWorkOrderBo.setPriceMasterId(bo.getPriceMasterId());
        saveWorkOrderBo.setContact(customerDetail.getCustomerName());
        saveWorkOrderBo.setContactPhone(customerDetail.getPhone());
        saveWorkOrderBo.setAddress(StrUtil.isNotBlank(bo.getAddress()) ? bo.getAddress() : saleOrderDetail.getInstallAddress());
        saveWorkOrderBo.setHouseNumber(customerDetail.getHouseNumber());
        saveWorkOrderBo.setMaintainId(installUserInfo.getCallCenterUserId());
        saveWorkOrderBo.setLongitude(coordinate.get("longitude"));
        saveWorkOrderBo.setLatitude(coordinate.get("latitude"));
        saveWorkOrderBo.setCustomerId(customerDetail.getUuid());
        saveWorkOrderBo.setEmergencyDegreeId(bo.getEmergencyDegreeId());
        saveWorkOrderBo.setSaleOrderName(saleOrderDetail.getSaleOrderName());
        saveWorkOrderBo.setPriceMasterName(priceMasterDetail.getName());
        saveWorkOrderBo.setXzqhdm(saleOrderDetail.getAreaCode());
        saveWorkOrderBo.setAgreedDoorstepTimeStart(bo.getAgreedDoorstepTimeStart());
        saveWorkOrderBo.setAgreedDoorstepTimeEnd(bo.getAgreedDoorstepTimeEnd());
        saveWorkOrderBo.setCustomerHouseId(Long.valueOf(priceMasterDetail.getBuildId()));
        saveWorkOrderBo.setOperateDate(bo.getOperateDate());
        Long workOrderId = callCenterService.createWorkOrder(saveWorkOrderBo, CallMethodEnum.SAVE_WORK_ORDER.url());
        CustomerHouseDTO houseDetail = customerHouseService.getHouseDetail(Long.valueOf(priceMasterDetail.getBuildId()));
        if (ObjectUtil.isNull(houseDetail)) {
            throw new IllegalBusinessException("房屋信息不存在！");
        }
        // 生成设备关联关系
        SaveWorkOrderEquipmentInfoBO saveWorkOrderEquipmentInfoBo = new SaveWorkOrderEquipmentInfoBO();
        BeanUtils.copyProperties(bo, saveWorkOrderEquipmentInfoBo);
        saveWorkOrderEquipmentInfoBo.setWorkOrderId(workOrderId);
        saveWorkOrderEquipmentInfoBo.setSaleOrderId(bo.getSaleOrderId());
        saveWorkOrderEquipmentInfoBo.setPriceMasterId(bo.getPriceMasterId());
        saveWorkOrderEquipmentInfoBo.setCustomerHouseId(houseDetail.getHouseUuid());
        equipmentService.saveWorkOrderEquipmentInfo(saveWorkOrderEquipmentInfoBo);

        // 插入工单-商机关系数据
        CrmFlowTableRelationshipBO crmFlowTableRelationshipBo = new CrmFlowTableRelationshipBO();
        crmFlowTableRelationshipBo.setOpportunityUuid(saleOrderDetail.getBusinessId());
        crmFlowTableRelationshipBo.setSaleOrderId(saleOrderDetail.getId());
        crmFlowTableRelationshipBo.setSalePriceMasterId(bo.getPriceMasterId());
        crmFlowTableRelationshipBo.setWorkOrderId(workOrderId);

        BatchSaveCrmFlowDataBO batchSaveCrmFlowDataBo = new BatchSaveCrmFlowDataBO();
        BeanUtils.copyProperties(bo, batchSaveCrmFlowDataBo);
        batchSaveCrmFlowDataBo.setDataList(Collections.singletonList(crmFlowTableRelationshipBo));
        crmFlowTableRelationshipService.batchInsertCrmFlowData(batchSaveCrmFlowDataBo);
        //更改项目状态，从待分配状态，更改为施工中
        TProject tProject = tProjectService.getProject(bo.getProjectId().toString());
        if (ObjectUtil.isNotEmpty(tProject)) {
            String projectStatus = tProject.getProjectStatus();
            if ("02".equals(projectStatus)) {
                ProjectAcceptanceVO vo = new ProjectAcceptanceVO();
                vo.setProjectStatus("04");
                tProjectService.projectAcceptance(vo);
            }
        } else {
            throw new IllegalBusinessException("根据项目id未查到项目");
        }
        return String.valueOf(workOrderId);
    }

    /**
     * 在热链云跨库查询全部工单分页接口
     */
    @Override
    public PageData getAllWorkOrderPage(GetAllWorkOrderPageVO vo) {
        // 准备返回值
        Page<GetAllWorkOrderPageDTO> page = new Page<>(vo.getPageid(), vo.getPagesize());

        // 处理用户的维度
        List<CcUser> ccUsers = ccUserService.selectList(vo.getErUserId());
        if (CollUtil.isEmpty(ccUsers)) {
            // 如果查询不到客服用户ID，不进行查询
            return PageData.okPage(new Page<>(vo.getPageid(), vo.getPagesize()));
        }
        List<Long> ccUserIds = ccUsers.stream().map(CcUser::getId).collect(Collectors.toList());
        vo.setCcUserIds(ccUserIds);
        // 处理行政区划代码
        vo.setXzqhdm(XzqhUtils.getRegionCodePrefix(vo.getXzqhdm()));
        // 处理查询类别
        Set<Long> queryWorkOrderIdSet = new HashSet<>();
        boolean flag = true;
        if (StrUtil.isNotBlank(vo.getWorkOrderState()) && WorkOrderStautsEnum._8.getKey().equals(vo.getWorkOrderState())) {
            flag = false;
            // 查询已分单的工单id集合
            QueryWrapper<WorkOrderRecord> queryWrapper = new QueryWrapper<>();
            queryWrapper.select("work_order_id");
            queryWrapper.eq("status", WorkOrderStautsEnum._8.getKey());
            queryWrapper.eq("effective_record", true);
            queryWrapper.in("user_id", ccUserIds);

            queryWorkOrderIdSet = workOrderRecordMapper.selectList(queryWrapper).stream().map(WorkOrderRecord::getWorkOrderId).collect(Collectors.toSet());
            if (CollectionUtil.isEmpty(queryWorkOrderIdSet)) {
                return PageData.okPage(new Page<>(vo.getPageid(), vo.getPagesize()));
            }
            // 设置查询已分单的工单参数
            vo.setQueryDistributedWorkOrder(true);
        } else {
            // 处理项目id
            if (StrUtil.isNotBlank(vo.getProjectId())) {
                queryWorkOrderIdSet = crmFlowTableRelationshipService.getWorkOrderIdSetByProjectId(Long.valueOf(vo.getProjectId()));
            }
        }

        // 查询工单分页
        vo.setWorkOrderIdSet(queryWorkOrderIdSet);
        List<GetAllWorkOrderPageDTO> records = callWorkOrderInfoService.queryOrderPage(page, vo);
        if (CollectionUtil.isEmpty(records)) {
            return PageData.okPage(page);
        }

        // 查询所有用户，方便根据用户ID获取用户信息
        List<CcUser> allUsers = ccUserService.selectList(null);
        Map<Long, CcUser> userMap = allUsers.stream().collect(Collectors.toMap(CcUser::getId, ccUser -> ccUser));

        // 查询所有公司，方便后续取值
        List<CcCompany> allCompanys = ccCompanyService.selectList();
        Map<Long, CcCompany> companyMap = allCompanys.stream()
                .collect(Collectors.toMap(CcCompany::getId, ccCompany -> ccCompany));

        // 获取工单对应项目id的Map
        Set<Long> workOrderIdSet = records.stream().map(GetAllWorkOrderPageDTO::getOrderId).collect(Collectors.toSet());
        Map<Long, Long> workOrderProjectIdMap = crmFlowTableRelationshipService.getWorkOrderProjectIdMap(workOrderIdSet);

        // 数据设置
        for (GetAllWorkOrderPageDTO record : records) {
            record.setOrderCreateSource(companyMap.get(record.getCompanyId()) == null ? "" : companyMap.get(record.getCompanyId()).getName());
            record.setOrderStatusDesc(WorkOrderStautsEnum.getVal(record.getOrderStatus()));
            record.setOrderServiceStatusDesc(WorkOrderServiceStautsEnum.getVal(record.getOrderServiceStatus()));
            record.setOrderCreateUserName(userMap.get(record.getCreateUserId()) == null ? "" : userMap.get(record.getCreateUserId()).getName());
            record.setEmergencyDegreeDesc(WorkOrderEmergencyDegreeEnum.getVal(record.getEmergencyDegreeId()));
            record.setWorkTypeDesc(OrderWorkTypeEnum.getVal(record.getWorkTypeId().intValue()));
            record.setProjectId(String.valueOf(workOrderProjectIdMap.get(record.getOrderId())));
            record.setInstallOrderEquipments(gGoodsService.queryInstallOrderEquipmentInfo(record.getOrderId()));
            record.setNeedToOperate(flag);
            // 如果工单不属于当前登录人 && 工单未完成 - 可以撤销
            if (!flag && WorkOrderStautsEnum.getStatusList(false).contains(String.valueOf(record.getOrderStatus()))) {
                record.setCanCancel(true);
            }
            CcUser ccUser = userMap.get(record.getMaintainId());
            if (ObjectUtil.isNotNull(ccUser)) {
                record.setInstallUserName(ccUser.getName());
                record.setInstallUserPhone(ccUser.getPhone());
            }
        }
        page.setRecords(records);

        return PageData.okPage(page);
    }

    /**
     * 查询安装工单分页 - 热链云PC端
     */
    @Override
    public PageData getWorkOrderInstallPage(GetWorkOrderInstallPageVO vo) throws Exception {
        // 准备返回值
        Page<GetWorkOrderInstallPageDTO> page = new Page<>(vo.getPageid(), vo.getPagesize());
        List<GetWorkOrderInstallPageDTO> records = new ArrayList<>();

        // 如果是创今公司账号 - 不需要以行政区划过滤
        if (CompanyIdEnum.NES_COMPANY.getKey().equals(vo.getOperateUserCompanyId())) {
            vo.setFilterByAreaCode(false);
        }
        // 判断是否需要以行政区划过滤
        if (vo.getFilterByAreaCode()) {
            // 如果没配置任何行政区划,就不用查询项目分页
            if (CollectionUtil.isEmpty(vo.getOperateUserAreaCodeSet())) {
                log.info("没配置任何行政区划,不用查询工单分页,操作人昵称:{},操作人id{}", vo.getOperateNickName(), vo.getOperateUserId());
                return PageData.ok(page, records);
            }
            // 如果配置的行政区划包含86 - 不按行政区划过滤
            if (!vo.getOperateUserAreaCodeSet().contains("86")) {
                // 获取行政区划的全部子集
                vo.setWorkOrderAreaCodeSet(xzqhService.getChildAreaCodesByParentAreaCodeSet(vo.getOperateUserAreaCodeSet(), true));
            }
        }

        // 处理参数
        QueryInstallWorkOrderBO queryBO = perHandleVO(vo);
        if (queryBO.getReturnEmpty()) {
            return PageData.ok(page, records);
        }
        vo.setAreaCode(XzqhUtils.getRegionCodePrefix(vo.getAreaCode()));

        // 查询安装工单分页信息
        records = this.baseMapper.getWorkOrderInstallPage(page, vo, queryBO);
        if (CollectionUtil.isEmpty(records)) {
            return PageData.ok(page, records);
        }

        return PageData.ok(page, postHandleResult(records));
    }

    /**
     * 查询安装工单详情
     */
    @Override
    public PageData getWorkOrderInstallDetail(GetWorkOrderInstallDetailVO vo) throws Exception {
        if (!CompanyTypeEnum._00.getKey().equals(vo.getOperateUserCompanyType())) {
            vo.setOrderCreateUserId(vo.getUserInfo().getUuid());
            vo.setOrderBelongCompanyId(vo.getOperateUserCallCenterCompanyId());
        }
        // 查询维修工单主体信息
        WorkOrderInstallDetailDTO workOrderInstallDetailDTO = callCenterService.getWorkOrderInstallDetail(vo.convertToBo());
        WorkOrderInstallInfoDTO workOrderInfo = workOrderInstallDetailDTO.getWorkOrderInfo();
        setWorkOrderInfoFields(vo, workOrderInfo);
        // 查询设备信息
        List<EquipmentInfoDTO> equipmentInfoList = equipmentService.getEquipmentInfoListByWorkOrderId(workOrderInfo.getId());
        // 查询客户基本信息
        CustomerDTO customerDetail = crmCustomerService.getCustomerById(workOrderInfo.getCustomerId());
        // 查询客户房屋信息
        CustomerHouseDTO houseInfo = customerHouseService.getHouseDetail(workOrderInfo.getCustomerHouseId());
        // 查询工单所属商机信息
        OpportunityInfoDto opportunityInfo = crmOpportunityService.getOpportunityDetailByWorkOrderId(workOrderInfo.getId());
        // 查询工单所属项目信息
        TProjectDTO projectDetail = new TProjectDTO();
        Long projectId = crmFlowTableRelationshipService.getProjectId(workOrderInfo.getId());
        if (projectId != null) {
            TProject tProject = tProjectService.getProjectDetail(projectId);
            BeanUtils.copyProperties(tProject, projectDetail);
        }

        // 组装客户信息
        customerDetail.setAddress(houseInfo.getAddress());
        customerDetail.setHouseNumber(houseInfo.getHouseNumber());
        customerDetail.setEnergyMeterNumber(houseInfo.getElectricityMeterNumbers());
        workOrderInfo.setHouseNumber(houseInfo.getHouseNumber());
        // 组装返回值参数
        workOrderInstallDetailDTO.setEquipmentInfoList(equipmentInfoList);
        workOrderInstallDetailDTO.setCustomerDetail(customerDetail);
        workOrderInstallDetailDTO.setHouseList(Collections.singletonList(houseInfo));
        workOrderInstallDetailDTO.setOpportunityInfo(opportunityInfo);
        workOrderInstallDetailDTO.setProjectDetail(projectDetail);
        return PageData.ok("workOrderInstallDetail", workOrderInstallDetailDTO);
    }

    /**
     * 约定上门时间
     */
    @Override
    public PageData updateDoorTime(UpdateDoorTimeVo vo) {
        long timeMillis = System.currentTimeMillis();
        Long workOrderId = vo.getWorkOrderId();
        // 查询工单信息
        WorkOrderInfo workOrderInfo = callWorkOrderInfoService.selectByPrimaryKey(workOrderId);
        if (ObjectUtil.isNull(workOrderInfo)) {
            throw new IllegalBusinessException("未查询到工单信息");
        }
        //修改工单状态
        workOrderInfo.setAgreedDoorstepTimeStart(vo.getAgreedDoorstepTimeStart());
        workOrderInfo.setAgreedDoorstepTimeEnd(vo.getAgreedDoorstepTimeEnd());
        workOrderInfo.setMaintainStatus((Integer.parseInt(MaintainWorkOrderStautsEnum._3.getKey())));
        callWorkOrderInfoService.updateByPrimaryKey(workOrderInfo);

        //新增工单记录
        workOrderRecordService.saveWorkOrderRecord(timeMillis, workOrderId, Integer.valueOf(WorkOrderStautsEnum._2.getKey()), "上门时间：" + vo.getAgreedDoorstepTimeStart() + " - " + vo.getAgreedDoorstepTimeEnd(), null, null, workOrderInfo.getMaintainId(), null);

        return PageData.ok("修改成功");
    }

    /**
     * 安装工单接单
     */
    @Override
    @CallCenterTransactional
    public PageData acceptOrderInstall(AcceptOrderInstallVo vo) {
        long timeMillis = System.currentTimeMillis();
        // 查询工单信息
        WorkOrderInfo workOrderInfo = callWorkOrderInfoService.selectByPrimaryKey(vo.getWorkOrderId());
        if (ObjectUtil.isNull(workOrderInfo)) {
            throw new IllegalBusinessException("未查询到工单信息");
        }

        //查询业务支持人员
        CcUser ccUser = ccUserService.getCcUser(workOrderInfo.getMaintainId());
        //修改工单状态 0 待处理
        workOrderInfo.setMaintainStatus((Integer.parseInt(MaintainWorkOrderStautsEnum._0.getKey())));
        callWorkOrderInfoService.updateByPrimaryKey(workOrderInfo);

        //更新业务支持人员坐标
        updateUserCoordinate(ccUser.getId(), vo.getLongitude(), vo.getLatitude(), vo.getOperateUserPhone());
        //新增工单记录
        workOrderRecordService.saveWorkOrderRecord(timeMillis, vo.getWorkOrderId(), Integer.valueOf(WorkOrderStautsEnum._2.getKey()), "已接单", vo.getLongitude(), vo.getLatitude(), ccUser.getId(), null);
        return PageData.ok("接单成功");
    }

    /**
     * 安装工单签到打卡
     */
    @Override
    @CallCenterTransactional
    public PageData punchClockOrderInstall(AcceptOrderInstallVo vo) {
        long timeMillis = vo.getOperateTimeStamp();
        // 查询工单信息
        WorkOrderInfo workOrderInfo = callWorkOrderInfoService.selectByPrimaryKey(vo.getWorkOrderId());
        if (ObjectUtil.isNull(workOrderInfo)) {
            throw new IllegalBusinessException("未查询到工单信息！");
        }

//   /*     if (!(workOrderInfo.getVerificationCode().equals(vo.getVerificationCode()))) {
//            throw new BusinessException("验证码错误！");
//        }*/
        //查询业务支持人员
        CcUser ccUser = ccUserService.getCcUser(workOrderInfo.getMaintainId());
        // 修改工单状态 1 已打卡
        workOrderInfo.setMaintainStatus((Integer.parseInt(MaintainWorkOrderStautsEnum._1.getKey())));
        callWorkOrderInfoService.updateByPrimaryKey(workOrderInfo);

        //更新业务支持人员坐标
        updateUserCoordinate(ccUser.getId(), vo.getLongitude(), vo.getLatitude(), vo.getOperateUserPhone());
        //新增工单记录
        workOrderRecordService.saveWorkOrderRecord(timeMillis, vo.getWorkOrderId(), Integer.valueOf(WorkOrderStautsEnum._2.getKey()), "已到达安装位置", vo.getLongitude(), vo.getLatitude(), ccUser.getId(), null);
        return PageData.ok("打卡成功");
    }

    /**
     * 安装工单拒单
     */
    @Override
    @CallCenterTransactional
    public PageData rejectionOrderInstall(RejectionOrderInstallVo vo) throws Exception {
        // 校验参数
        validate(vo);
        // 准备必要参数
        boolean isCaptain = false;
        // 查询是否属于团队
        boolean belongToTeam = projectServiceUserAuthService.validateBelongToTeam(vo.getOperateUserId(), vo.getProjectUuid());
        if (belongToTeam) {
            // 查询是否为当前项目的队长
            isCaptain = projectServiceUserAuthService.validateHeadAuth(vo.getOperateUserId(), vo.getProjectUuid());
        }

        // 如果属于团队 & 不是队长
        if (belongToTeam && !isCaptain) {
            // 查询我的队长
            TUser captainUserInfo = projectServiceUserAuthService.getMyCaptain(vo.getOperateUserId(), vo.getProjectUuid());
            // 转单给队长
            TransferOrderInstallVo transferOrderInstallVo = new TransferOrderInstallVo();
            BeanUtils.copyProperties(vo, transferOrderInstallVo);
            transferOrderInstallVo.setTransferOrder(true);
            transferOrderInstallVo.setOrderId(vo.getWorkOrderId());
            transferOrderInstallVo.setMaintainId(String.valueOf(captainUserInfo.getId()));
            transferOrderInstallVo.setTransferDesc(vo.getDesc());
            PageData result = this.transferOrderInstall(transferOrderInstallVo);
            if (result.getRetCode() != 0) {
                return PageData.ok("拒单失败,失败原因:" + result.getRetMessage());
            }

            // 保存拒单记录
            WorkOrderRejectionInfoBO workOrderRejectionInfoBO = new WorkOrderRejectionInfoBO();
            workOrderRejectionInfoBO.setOperateUserId(vo.getOperateUserId());
            workOrderRejectionInfoBO.setOperateDate(vo.getOperateDate());
            workOrderRejectionInfoBO.setWorkOrderId(vo.getWorkOrderId());
            workOrderRejectionInfoBO.setRemark(vo.getDesc());
            workOrderRejectionInfoBO.setType(WorkOrderRejectionTypeEnum.TEAM_MEMBER.getKey());
            workOrderRejectionInfoService.insertWorkOrderRejectionInfo(workOrderRejectionInfoBO);

            // 给队长发送新工单通知
            try {
                String title = "新的拒单通知";
                String body = "您的队员已拒单，点击查看详情。";

                Map<String, String> sendParams = new HashMap<>();
                sendParams.put("workOrderType", "install");
                sendParams.put("workOrderId", String.valueOf(vo.getWorkOrderId()));
                sendParams.put("companyId", vo.getOperateUserCompanyId());
                sendMessageHandler.sendWorkOrderMessageToEasyRepair(title, body, Collections.singletonList(captainUserInfo.getPhone()), sendParams);
            } catch (Exception e) {
                log.error("拒单后发送通知消息失败,失败原因:{}", e.getMessage());
                e.printStackTrace();
            }

            return PageData.ok("拒单成功");
        }

        // 如果不属于团队 或 是队长
        Long workOrderId = vo.getWorkOrderId();

        // 封装工单表数据
        WorkOrderInfo workOrderInfo = new WorkOrderInfo();
        workOrderInfo.setId(workOrderId);
        workOrderInfo.setStatus(Integer.valueOf(WorkOrderStautsEnum._0.getKey()));
        workOrderInfo.setGmtModified(vo.getOperateTimeStamp());
        // 修改工单表中的状态
        int result = callWorkOrderInfoService.rejectionOrderInstall(workOrderInfo);

        // 判断是否修改成功工单表状态
        if (result > 0) {
            // 写工单记录，返回工单记录id
            StringBuilder remark = new StringBuilder("已拒单;");
            remark.append("拒单描述:").append(vo.getDesc());
            workOrderRecordService.saveWorkOrderRecord(vo.getOperateTimeStamp(), workOrderId, Integer.valueOf(WorkOrderStautsEnum._0.getKey()), String.valueOf(remark), null, null, vo.getUserInfo().getCallCenterUserId(), null);

            // 更新工单操作记录 - 将历史转单记录设置为失效
            workOrderRecordService.updateWorkOrderRecord(workOrderId);

            // 保存拒单记录
            WorkOrderRejectionInfoBO workOrderRejectionInfoBO = new WorkOrderRejectionInfoBO();
            workOrderRejectionInfoBO.setOperateUserId(vo.getOperateUserId());
            workOrderRejectionInfoBO.setOperateDate(vo.getOperateDate());
            workOrderRejectionInfoBO.setWorkOrderId(vo.getWorkOrderId());
            workOrderRejectionInfoBO.setRemark(vo.getDesc());
            workOrderRejectionInfoBO.setType(WorkOrderRejectionTypeEnum.CAPTAIN.getKey());
            workOrderRejectionInfoService.insertWorkOrderRejectionInfo(workOrderRejectionInfoBO);
        }
        return PageData.ok("拒单成功");
    }

    /**
     * 单条转单
     */
    @Override
    @CallCenterTransactional
    public PageData transferOrderInstall(TransferOrderInstallVo vo) throws Exception {
        // 查询安装工单信息
        WorkOrderInfo workOrderInfo = callWorkOrderInfoService.selectByPrimaryKey(vo.getOrderId());
        if (ObjectUtil.isNull(workOrderInfo)) {
            throw new IllegalBusinessException("未查询到工单信息！");
        }
        // 转换安装人id
        TUser installUserInfo = vo.getInstallUserInfo();
        if (ObjectUtil.isNull(installUserInfo)) {
            installUserInfo = systemUserService.getUserInfoByUserId(vo.getMaintainId());
            if (ObjectUtil.isNull(installUserInfo) || ObjectUtil.isNull(installUserInfo.getCallCenterUserId())) {
                throw new IllegalBusinessException("转换安装人id异常,安装人信息:" + JSON.toJSONString(installUserInfo));
            }
            vo.setInstallUserInfo(installUserInfo); // 反向传递到调用端
        }
        // 修改工单状态 - 恢复到派单的状态：处理中 + 未接单
        workOrderInfo.setStatus(Integer.valueOf(WorkOrderStautsEnum._2.getKey()));
        workOrderInfo.setMaintainStatus(Integer.valueOf(MaintainWorkOrderStautsEnum._3.getKey()));
        // 绑定新的安装人员
        workOrderInfo.setMaintainId(installUserInfo.getCallCenterUserId());
        workOrderInfo.setGmtModified(vo.getOperateTimeStamp());
        //修改工单表中的状态
        int rows = callWorkOrderInfoService.updateByPrimaryKey(workOrderInfo);
        if (1 != rows) {
            throw new IllegalBusinessException("转单/重新派单失败!");
        }

        //更新业务支持人员坐标
        updateUserCoordinate(installUserInfo.getCallCenterUserId(), vo.getLongitude(), vo.getLatitude(), vo.getOperateUserPhone());

        // 记录工单操作日志
        StringBuilder remark = new StringBuilder(StrUtil.EMPTY);
        if (vo.getTransferOrder()) {
            // 如果是转单
            remark.append("转单给:").append(installUserInfo.getNickName()).append(";");
            remark.append("转单描述:").append(vo.getTransferDesc());
            workOrderRecordService.saveWorkOrderRecord(vo.getOperateTimeStamp(), vo.getOrderId(), Integer.valueOf(WorkOrderStautsEnum._2.getKey()), String.valueOf(remark), vo.getLatitude(), vo.getLongitude(), vo.getUserInfo().getCallCenterUserId(), null);
        } else {
            // 校验接单人身份
            DistributeWorkOrderInstallBO bo = new DistributeWorkOrderInstallBO();
            bo.setMaintainId(vo.getMaintainId());
            bo.setProjectId(crmFlowTableRelationshipService.getProjectId(workOrderInfo.getId()));
            validateInstallUserAuth(bo, workOrderInfo.getXzqhdm());
            // 如果是重新派单
            if (StrUtil.isBlank(vo.getTransferDesc())) {
                remark.append("重新派单给:");
            } else {
                remark.append(vo.getTransferDesc());
            }
            remark.append(installUserInfo.getNickName());
            workOrderRecordService.saveWorkOrderRecord(vo.getOperateTimeStamp(), vo.getOrderId(), Integer.valueOf(WorkOrderStautsEnum._2.getKey()), String.valueOf(remark), vo.getLatitude(), vo.getLongitude(), installUserInfo.getCallCenterUserId(), vo.getUserInfo().getCallCenterUserId());
        }

        // 修改销售订单派单状态
        if (ObjectUtil.isNotNull(workOrderInfo.getPriceMasterId())) {
            salePriceService.changeStatus(workOrderInfo.getPriceMasterId(), true);
        }

        // 废弃安装工单的拒单记录
        InitRejectionInfoBO initRejectionInfoBO = vo.convertToBo(InitRejectionInfoBO.class);
        initRejectionInfoBO.setWorkOrderId(workOrderInfo.getId());
        workOrderRejectionInfoService.initRejectionInfo(initRejectionInfoBO);

        return PageData.ok("转单/重新派单成功");
    }

    /**
     * 批量转单
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void batchTransferOrderInstall(TransferOrderInstallBO bo) {
        if (CollectionUtil.isEmpty(bo.getWorkOrderIdList())) {
            throw new IllegalBusinessException("workOrderIdList must not empty");
        }
        if (ObjectUtil.isNull(bo.getMaintainId())) {
            throw new IllegalBusinessException("maintainId must not null");
        }
        if (ObjectUtil.isNull(bo.getUserId())) {
            throw new IllegalBusinessException("userId must not null");
        }

        // 批量修改工单的处理人
        WorkOrderInfo workOrderInfo = new WorkOrderInfo();
        // 修改工单状态 - 恢复到派单的状态：处理中 + 未接单
        workOrderInfo.setStatus(Integer.valueOf(WorkOrderStautsEnum._2.getKey()));
        workOrderInfo.setMaintainStatus(Integer.valueOf(MaintainWorkOrderStautsEnum._3.getKey()));
        workOrderInfo.setMaintainId(bo.getMaintainId());  // 绑定新的安装人员
        workOrderInfo.setGmtModified(bo.getOperateTimeStamp());

        QueryWrapper<WorkOrderInfo> wrapper = new QueryWrapper<>();
        wrapper.in("id", bo.getWorkOrderIdList());

        boolean success = this.update(workOrderInfo, wrapper);
        if (!success) {
            throw new IllegalBusinessException("批量修改工单处理人失败!");
        }
    }

    /**
     * 安装工单补充房屋信息
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public PageData replenishHouseInfo(ReplenishHouseInfoVO vo) throws Exception {
        customerHouseService.replenishHouseInfo(vo);
        return PageData.ok();
    }

    /**
     * 补充房屋信息相关下拉框
     */
    @Override
    public PageData replenishHouseDropdownBox(NullVO vo) throws Exception {
        Map<String, Object> map = new HashMap<>();
        map.put(DictTypeEnum.BUILDING_STRUCTURE.getTypeNameEN(), tParamService.getListMap(DictTypeEnum.BUILDING_STRUCTURE.getParamType()));
        map.put(DictTypeEnum.HEATING_MODE.getTypeNameEN(), tParamService.getListMap(DictTypeEnum.HEATING_MODE.getParamType()));
        map.put(DictTypeEnum.HOUSE_PERPOSE.getTypeNameEN(), tParamService.getListMap(DictTypeEnum.HOUSE_PERPOSE.getParamType()));
        map.put(DictTypeEnum.WINDOW_TYPE.getTypeNameEN(), tParamService.getListMap(DictTypeEnum.WINDOW_TYPE.getParamType()));
        map.put(DictTypeEnum.HOUSE_DIRECTION.getTypeNameEN(), tParamService.getListMap(DictTypeEnum.HOUSE_DIRECTION.getParamType()));
        map.put(DictTypeEnum.END_STATE.getTypeNameEN(), tParamService.getListMap(DictTypeEnum.END_STATE.getParamType()));
        map.put(DictTypeEnum.HEATING_END.getTypeNameEN(), tParamService.getListMap(DictTypeEnum.HEATING_END.getParamType()));
        map.put(DictTypeEnum.OUTER_WALL_THICKNESS.getTypeNameEN(), tParamService.getListMap(DictTypeEnum.OUTER_WALL_THICKNESS.getParamType()));
        map.put(DictTypeEnum.INSTALL_POSITION.getTypeNameEN(), tParamService.getListMap(DictTypeEnum.INSTALL_POSITION.getParamType()));

        return PageData.ok(map);
    }

    /**
     * 查询当前公司设备列表 - 下拉框，不分页
     */
    @Override
    public PageData getGoodsList(QueryGoodsListByWorkOrderVO vo) {
        List<GGoodsDTO> goodsList = new ArrayList<>();
        // 如果没传工单id - 查询本公司所有产品
        if (ObjectUtil.isNull(vo.getWorkOrderId())) {
            goodsList = gGoodsService.getGoodsListByCompanyId(vo.getOperateUserCompanyId());
            return PageData.ok("goodsList", goodsList);
        }

        // 根据安装工单id查询项目id
        Long projectId = crmFlowTableRelationshipService.getProjectId(vo.getWorkOrderId());
        if (ObjectUtil.isNull(projectId)) {
            return PageData.ok("goodsList", goodsList);
        }
        // 查询当前项目绑定的产品
        TProject project = tProjectService.getProjectDetail(projectId);
        if (ObjectUtil.isNull(project)) {
            return PageData.ok("goodsList", goodsList);
        }
        List<String> parts = Arrays.asList(project.getDeviceModels().split(";"));
        goodsList = gGoodsService.getGoodsListBySblxId(vo.getOperateUserCompanyId(), parts);

        return PageData.ok("goodsList", goodsList);
    }

    /**
     * 修改安装工单产品信息 - 派单前修改
     */
    @Override
    public PageData updatePriceDetail(UpdatePriceDetailVO vo) throws Exception {
        // 修改安装工单产品信息
        salePriceService.updatePriceDetail(vo);
        return PageData.ok();
    }

    /**
     * 安装工单修改设备dtu - 在创建安装工单的时候已经有设备信息了
     */
    @Override
    @CallCenterTransactional
    public void updateInstallEquipment(UpdateInstallEquipmentVO vo) throws Exception {
        List<InstallEquipmentVO> installEquipmentList = vo.getInstallEquipmentList().stream().filter(ObjectUtil::isNotNull).collect(Collectors.toList());
        if (CollectionUtil.isEmpty(installEquipmentList)) {
            throw new BusinessException("请选择要安装的设备");
        }

        List<EquipmentInfoDTO> equipmentInfoList = equipmentService.getEquipmentInfoListByWorkOrderId(vo.getWorkOrderId());
        List<EquipmentInfoDTO> deleteList = new ArrayList<>();
        List<EquipmentInfoDTO> updateList = new ArrayList<>();
        List<IsEquipmentInfo> insertList = new ArrayList<>();

        // 取出需要删除的和需要更新的
        if (CollectionUtil.isNotEmpty(equipmentInfoList)) {
            equipmentInfoList.forEach(item -> {
                long count = installEquipmentList.stream().filter(n -> StrUtil.isNotBlank(n.getSbId()) && n.getSbId().equals(item.getSbId())).count();
                if (count <= 0) {
                    // 取出需要删除的
                    deleteList.add(item);
                } else {
                    // 取出需要更新的
                    updateList.add(item);
                }
            });
        }

        // 查询产品名称
        Set<String> sblxIdSet = installEquipmentList.stream().map(InstallEquipmentVO::getSblxId).collect(Collectors.toSet());
        Map<String, String> goodsNameMap = gGoodsService.getGoodsMap(sblxIdSet);

        // 修改设备信息
        for (InstallEquipmentVO installEquipmentVO : installEquipmentList) {
            IsEquipmentInfo isEquipmentInfo = new IsEquipmentInfo();
            isEquipmentInfo.setSblxId(installEquipmentVO.getSblxId());
            isEquipmentInfo.setSbxlh(installEquipmentVO.getDeviceSerialNumber());
            isEquipmentInfo.setBdzt(1);
            isEquipmentInfo.setWxId(installEquipmentVO.getDtuId());
            isEquipmentInfo.setAlias(goodsNameMap.get(installEquipmentVO.getSblxId()));
            isEquipmentInfo.setBz("安装人员手动修改设备信息");

            // 判断是否是更新
            EquipmentInfoDTO item = updateList.stream().filter(n -> n.getSbId().equals(installEquipmentVO.getSbId())).findFirst().orElse(null);
            if (ObjectUtil.isNotNull(item) && ObjectUtil.isNotNull(item.getId())) {
                isEquipmentInfo.setId(item.getId());
                // 保存设备信息
                Integer rows = equipmentService.saveEquipmentInfo(isEquipmentInfo);
                if (rows <= 0) {
                    throw new IllegalBusinessException("更新设备信息失败！");
                }
            } else {
                insertList.add(isEquipmentInfo);
            }
        }

        // 查询安装工单信息
        WorkOrderInfo workOrderInfo = this.getWorkOrderInfo(vo.getWorkOrderId());
        // 查询地点id
        CustomerHouseDTO houseDetail = customerHouseService.getHouseDetail(workOrderInfo.getCustomerHouseId());
        // 新增设备信息
        for (IsEquipmentInfo isEquipmentInfo : insertList) {
            isEquipmentInfo.setManufactureId(vo.getUserInfo().getNes_companyId());
            isEquipmentInfo.setDdId(houseDetail.getHouseUuid());
            isEquipmentInfo.setScddh(String.valueOf(workOrderInfo.getSaleOrderId()));
            isEquipmentInfo.setJd(workOrderInfo.getLongitude());
            isEquipmentInfo.setWd(workOrderInfo.getLatitude());
            isEquipmentInfo.setWorkOrderId(workOrderInfo.getId());
            isEquipmentInfo.setUpOper(String.valueOf(vo.getOperateUserId()));
            isEquipmentInfo.setCreateOper(String.valueOf(vo.getOperateUserId()));

            // 保存设备信息
            Integer rows = equipmentService.saveEquipmentInfo(isEquipmentInfo);
            if (rows <= 0) {
                throw new IllegalBusinessException("更新设备信息失败！");
            }
        }

        // 删除设备信息
        if (CollectionUtil.isNotEmpty(deleteList)) {
            for (EquipmentInfoDTO item : deleteList) {
                equipmentService.delEquipmentInfoById(item.getId());
            }
        }
    }

    /**
     * 保存安装工单图片信息
     */
    @Override
    @CallCenterTransactional
    public PageData updatePicInfo(UpdatePicInfoVO vo) throws Exception {
        WorkOrderInfo workOrderInfo = callWorkOrderInfoService.selectByPrimaryKey(vo.getWorkOrderId());
        if (ObjectUtil.isNull(workOrderInfo)) {
            throw new BusinessException("工单信息不存在");
        }
        // 保存图片信息
        callWorkOrderPicService.insertPicInfo(vo);
        // 保存工单操作记录
        CcUser ccUser = ccUserService.getCcUser(workOrderInfo.getMaintainId());
        //写工单记录，返回工单记录id
        workOrderRecordService.saveWorkOrderRecord(vo.getOperateTimeStamp(), workOrderInfo.getId(),
                workOrderInfo.getStatus(), "保存安装工单图片", null, null,
                ccUser.getId(), vo.getUserInfo().getCallCenterUserId());
        return PageData.ok();
    }

    /**
     * 完成安装工单
     */
    @Override
    @CallCenterTransactional
    public PageData completeOrderInstall(CompleteOrderInstallVo vo) throws Exception {
        //获取当前工单id
        Long workOrderId = vo.getWorkOrderId();
        //封装工单表数据
        WorkOrderInfo workOrderInfo = callWorkOrderInfoService.selectByPrimaryKey(workOrderId);
        if (ObjectUtil.isNull(workOrderInfo)) {
            throw new IllegalBusinessException("未查询到工单信息！");
        }

        //保存安装信息
        workOrderInfo.setInstallState(vo.getInstallState());
        workOrderInfo.setInstallDate(vo.getInstallDate());
        workOrderInfo.setQualityGuaranteeYears(String.valueOf(vo.getQualityGuaranteeYears()));
        workOrderInfo.setProcureSource(vo.getProcureSource());
        workOrderInfo.setProcureFund(vo.getProcureFund());
        //修改工单表中的状态
        workOrderInfo.setMaintainStatus(Integer.valueOf(MaintainWorkOrderStautsEnum._2.getKey()));
        workOrderInfo.setStatus(Integer.valueOf(WorkOrderStautsEnum._7.getKey()));
        workOrderInfo.setGmtModified(vo.getOperateTimeStamp());
        workOrderInfo.setLatitude(vo.getLatitude());
        workOrderInfo.setLongitude(vo.getLongitude());
        int result = callWorkOrderInfoService.updateByPrimaryKey(workOrderInfo);

        CcUser ccUser = ccUserService.getCcUser(workOrderInfo.getMaintainId());

        updateUserCoordinate(ccUser.getId(), vo.getLongitude(), vo.getLatitude(), vo.getOperateUserPhone());
        //判断是否修改成功工单表状态
        if (result > 0) {
            //写工单记录，返回工单记录id
            WorkOrderRecord workOrderRecord = new WorkOrderRecord();
            workOrderRecord.setWorkOrderId(workOrderId);
            workOrderRecord.setDesc("安装完成");
            workOrderRecord.setMaintainId(ccUser.getId());
            workOrderRecord.setStatus(workOrderInfo.getStatus());
            workOrderRecord.setIsDelete(DeleteEnum._0.getKey());
            workOrderRecord.setGmtCreate(vo.getOperateTimeStamp());
            workOrderRecord.setGmtModified(vo.getOperateTimeStamp());
            workOrderRecord.setLongitude(vo.getLongitude());
            workOrderRecord.setLatitude(vo.getLatitude());
            workOrderRecordService.saveWorkOrderRecord(workOrderRecord);
        }

        //保存安装工单图片信息
        UpdatePicInfoVO updatePicInfoVO = new UpdatePicInfoVO();
        BeanUtils.copyProperties(vo, updatePicInfoVO);
        updatePicInfoVO.setWorkOrderId(workOrderId);
        updatePicInfoVO.setSavePicList(vo.getSavePicList());
        updatePicInfoVO.setUserInfo(vo.getUserInfo());
        updatePicInfoVO.setOperateDate(vo.getOperateDate());
        callWorkOrderPicService.insertPicInfo(updatePicInfoVO);

        // 保存设备安装信息
        try {
            SaveInstallInfoBO saveInstallInfoBo = new SaveInstallInfoBO();
            BeanUtils.copyProperties(vo, saveInstallInfoBo);
            saveInstallInfoBo.setWorkOrderId(workOrderId);
            saveInstallInfoBo.setWorkOrderInfo(workOrderInfo);
            saveInstallInfoBo.setHandleUserInfo(ccUser);
            saveInstallInfoBo.setSavePicList(vo.getSavePicList());
            isInstallInfoService.saveInstallInfo(saveInstallInfoBo);
        } catch (Exception e) {
            log.info("保存安装信息失败,失败原因:{}", e.getMessage());
        }

        return PageData.ok("成功");
    }

    /**
     * 查询安装信息相关下拉框
     */
    @Override
    public PageData getInstallInfoDropdownBox(NullVO vo) throws Exception {
        Map<String, Object> map = new HashMap<>();
        map.put(DictTypeEnum.INSTALL_STATE.getTypeNameEN(), tParamService.getListMap(DictTypeEnum.INSTALL_STATE.getParamType()));
        map.put(DictTypeEnum.PROCURE_SOURCE.getTypeNameEN(), tParamService.getListMap(DictTypeEnum.PROCURE_SOURCE.getParamType()));

        return PageData.ok(map);
    }

    /**
     * 查询紧急程度下拉框
     */
    @Override
    public PageData getEmergencyDegreeDropdownBox(NullVO vo) {
        return PageData.ok(WorkOrderEmergencyDegreeEnum.getListMap());
    }

    /**
     * 查询安装工单时间轴
     */
    @Override
    public PageData getWorkOrderInstallTimeAxis(GetWorkOrderInstallDetailVO vo) {
        return callWorkOrderInfoService.getWorkOrderInstallTimeAxis(vo.getWorkOrderId());
    }

    /**
     * 查询安装工单信息
     */
    @Override
    public WorkOrderInfo getWorkOrder(Long saleOrderSystemId) {
        QueryWrapper<WorkOrderInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("is_delete", 0);
        queryWrapper.eq("type", WorkOrderTypeEnum._4.getKey());
        queryWrapper.eq("price_master_id", saleOrderSystemId);
        return this.getOne(queryWrapper);
    }

    /**
     * 查询安装工单信息
     */
    @Override
    public WorkOrderInfo getWorkOrderInfo(Long workOrderId) {
        return this.baseMapper.selectById(workOrderId);
    }

    /**
     * 校验客户是否拥有安装工单
     */
    @Override
    public Boolean checkHaveWorkOrder(String customerId) {
        Integer count = this.baseMapper.getWorkOrderCountByCustomerId(customerId);
        return count > 0;
    }

    /**
     * 查询工单列表
     */
    @Override
    public List<WorkOrderInfo> getWorkOrderList(Long projectId, String areaCode) {
        if (ObjectUtil.isNull(projectId)) {
            throw new IllegalBusinessException("projectId must not null");
        }
        Set<Long> workOrderIdSet = crmFlowTableRelationshipService.getWorkOrderIdSetByProjectId(projectId);
        if (CollectionUtil.isEmpty(workOrderIdSet)) {
            return Collections.emptyList();
        }

        QueryWrapper<WorkOrderInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.in("id", workOrderIdSet);
        queryWrapper.eq("is_delete", 0);
        queryWrapper.eq("type", WorkOrderTypeEnum._4.getKey());
        if (StrUtil.isNotBlank(areaCode)) {
            queryWrapper.likeRight("xzqhdm", XzqhUtils.getRegionCodePrefix(areaCode));
        }
        return this.baseMapper.selectList(queryWrapper);
    }

    /**
     * 查询客户的拒单情况
     */
    @Override
    public List<CustomerRefusalWorkOrderInfoDTO> getCustomerRefusalWorkOrderInfo(List<String> customerIdList, Set<Long> workOrderIdSet) {
        return callWorkOrderInfoService.getCustomerRefusalWorkOrderInfo(customerIdList, workOrderIdSet);
    }

    /**
     * 根据项目id查询派单个数
     */
    @Override
    public Integer getDispatchedCount(Long projectId) {
        Set<Long> workOrderIdSet = crmFlowTableRelationshipService.getWorkOrderIdSetByProjectId(projectId);
        if (CollectionUtil.isEmpty(workOrderIdSet)) {
            return 0;
        }

        QueryWrapper<WorkOrderInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.in("id", workOrderIdSet);
        queryWrapper.isNotNull("maintain_id");
        queryWrapper.eq("is_delete", DeleteEnum._0.getKey());
        queryWrapper.ne("status", WorkOrderStautsEnum._0.getKey());
        queryWrapper.eq("type", WorkOrderTypeEnum._4.getKey());
        return this.baseMapper.selectCount(queryWrapper);
    }

    @Override
    public HashMap<String, Integer> getAuditedCount(Long projectId) {
        Set<Long> workOrderIdSet = crmFlowTableRelationshipService.getWorkOrderIdSetByProjectId(projectId);
        HashMap<String, Integer> hashMap = new HashMap<>();
        if (CollectionUtil.isEmpty(workOrderIdSet)) {
            hashMap.put("count", 0);
            hashMap.put("auditedCount", 0);
            hashMap.put("notAuditedCount", 0);
            return hashMap;
        }
        QueryWrapper<WorkOrderInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.in("id", workOrderIdSet);
        queryWrapper.isNotNull("maintain_id");
        queryWrapper.eq("is_delete", DeleteEnum._0.getKey());
        queryWrapper.eq("status", WorkOrderStautsEnum._3.getKey());
        queryWrapper.eq("type", WorkOrderTypeEnum._4.getKey());
        queryWrapper.and(wrapper -> wrapper.eq("audited", AuditedEnum._1.getKey()).
        or().
        eq("audited", AuditedEnum._2.getKey()));

        hashMap.put("count", workOrderIdSet.size());
        hashMap.put("auditedCount", Integer.parseInt(this.baseMapper.selectCount(queryWrapper) + ""));
        QueryWrapper<WorkOrderInfo> queryWrapperNum = new QueryWrapper<>();
        queryWrapperNum.in("id", workOrderIdSet);
        queryWrapperNum.isNotNull("maintain_id");
        queryWrapperNum.eq("is_delete", DeleteEnum._0.getKey());
        queryWrapperNum.eq("status", WorkOrderStautsEnum._7.getKey());
        queryWrapperNum.eq("type", WorkOrderTypeEnum._4.getKey());
        queryWrapperNum.eq("audited", AuditedEnum._0.getKey());
        hashMap.put("notAuditedCount", Integer.parseInt(this.baseMapper.selectCount(queryWrapperNum) + ""));
        return hashMap;
    }


    /**
     * 查询当前客户全部被拒单的工单id
     *
     * @param customerIdList 客户id
     * @param isRefusal      是否被拒单 true-被拒单 false-没拒单
     * @return 工单id列表
     */
    @Override
    public Set<WorkOrderInfo> getWorkOrderInfoSetByCustomerId(List<String> customerIdList, Boolean isRefusal) {
        // 查询当前客户被拒单的工单列表
        QueryWrapper<WorkOrderInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.select("id", "customer_id");
        queryWrapper.eq("is_delete", 0);
        queryWrapper.eq("type", WorkOrderTypeEnum._4.getKey());
        queryWrapper.in("customer_id", customerIdList);
        if (isRefusal) {
            queryWrapper.isNull("maintain_id");
            queryWrapper.eq("status", 0);
        }
        List<WorkOrderInfo> workOrderInfoList = this.baseMapper.selectList(queryWrapper);
        if (CollectionUtil.isEmpty(workOrderInfoList)) {
            return Collections.emptySet();
        }
        // 返回被拒单的工单id
        return new HashSet<>(workOrderInfoList);
    }

    /**
     * 根据派单情况查询客户id列表
     *
     * @param isDispatched 是否已派单 0-未派单 1-已派单 null-全部
     */
    @Override
    public List<String> getCustomerIdListByDispatched(Integer isDispatched, Integer audited) {
        return this.baseMapper.getCustomerIdListByDispatched(isDispatched, audited);
    }

    /**
     * 查询我团队的工单
     */
    @Override
    public Page<GetWorkOrderInstallPageDTO> getMyTeamWorkOrderInstallPage(GetTeamWorkOrderInstallPageBO bo) throws Exception {
        // 校验入参
        validate(bo);

        // 准备必要参数
        TProjectDTO projectInfo = tProjectService.getProjectDetail(bo.getProjectUuid());
        if (ObjectUtil.isNull(projectInfo)) {
            throw new IllegalBusinessException("当前项目不存在");
        }
        Page<GetWorkOrderInstallPageDTO> page = new Page<>(bo.getPageid(), bo.getPagesize());
        page.setTotal(0);
        page.setRecords(Collections.emptyList());
        // 查询项目上队长的信息
        TUser captainAgentUserInfo = systemUserService.getServiceUserInfo(bo.getProjectUuid(), bo.getEasyRepairUserId());
        if (ObjectUtil.isNull(captainAgentUserInfo) || ObjectUtil.isNull(captainAgentUserInfo.getCallCenterUserId())) {
            throw new IllegalBusinessException("长效管护用户信息不存在");
        }
        // 查询行政区划编码结果集 - area_code List
        Set<String> areaCodeList = getAllAreaCode(bo, captainAgentUserInfo.getId());
        if (CollectionUtil.isEmpty(areaCodeList)) {
            return page;
        }
        // 按项目id查询工单id集合
        Set<Long> workOrderIdSet = crmFlowTableRelationshipService.getWorkOrderIdSetByProjectId(projectInfo.getId());
        if (CollectionUtil.isEmpty(workOrderIdSet)) {
            return page;
        }

        // 获取是否分单 - status & maintain_status
        Integer distributeStatus = bo.getDistributeStatus();

        // 查询工单分页 - 组装查询参数
        QueryWrapper<WorkOrderInfo> wrapper = new QueryWrapper<>();
        wrapper.in("id", workOrderIdSet);
        wrapper.eq("is_delete", false);
        wrapper.eq("type", WorkOrderTypeEnum._4.getKey());
        wrapper.in("xzqhdm", areaCodeList);
        if (ObjectUtil.isNotNull(distributeStatus)) {
            if (GetTeamWorkOrderInstallPageVO.UN_DISTRIBUTE.equals(distributeStatus)) {
                // 未分单 - id是自己 & status = 2 & maintain_status = 3
                wrapper.eq("maintain_id", captainAgentUserInfo.getCallCenterUserId());
                wrapper.eq("status", WorkOrderStautsEnum._2.getKey());
                wrapper.eq("maintain_status", MaintainWorkOrderStautsEnum._3.getKey());
            } else if (GetTeamWorkOrderInstallPageVO.DISTRIBUTE.equals(distributeStatus)) {
                // 已分单 - id不是自己
                wrapper.ne("maintain_id", captainAgentUserInfo.getCallCenterUserId());
            }
        }
        if (StrUtil.isNotBlank(bo.getKeyWord())) {
            // 根据keyWord处理门牌号
            List<Long> houseIdList = handleHouseNumber(bo.getKeyWord());
            wrapper.and(wrapper1 ->  {
                if (CollectionUtil.isNotEmpty(houseIdList)) {
                    wrapper1.in("customer_house_id", houseIdList).or();
                }
                wrapper1.like("contact", bo.getKeyWord()).or();
                wrapper1.like("contact_phone", bo.getKeyWord());
            });

        }
        wrapper.orderByDesc("gmt_create");

        // 查询工单分页
        Page<WorkOrderInfo> queryPage = new Page<>(bo.getPageid(), bo.getPagesize());
        Page<WorkOrderInfo> workOrderInfoPage = (Page<WorkOrderInfo>) this.page(queryPage, wrapper);

        // 设置出参字段
        List<GetWorkOrderInstallPageDTO> myTeamWorkOrderInstallList = getMyTeamWorkOrderInstallRecords(workOrderInfoPage.getRecords(), bo.getEasyRepairUserId());
        // 返回结果集
        page.setTotal(queryPage.getTotal());
        page.setRecords(myTeamWorkOrderInstallList);
        return page;
    }

    /**
     * 分单
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public PageData distributeWorkOrder(EasyRepairDistributeWorkOrderVO vo) throws Exception {
        // 校验入参的工单是否符合要求：
        // 1、所有工单id必须在同一个项目下
        List<Long> projectIdList = crmFlowTableRelationshipService.getProjectIdList(vo.getWorkOrderIdList());
        if (CollectionUtil.isEmpty(projectIdList) || projectIdList.size() > 1) {
            throw new BusinessException("您选择的安装工单不在同一个项目下,请重新选择工单后分单");
        }
        // 获取userInfo - 因为这个接口是无鉴权接口,所以需要手动获取userInfo
        Long userId = projectServiceUserAuthService.getUserIdByProjectId(projectIdList.get(0), vo.getEasyRepairUserId(), Boolean.TRUE);
        TUser captainUserInfo = systemUserService.getUserInfoByUserId(String.valueOf(userId));
        if (ObjectUtil.isNull(captainUserInfo)) {
            throw new IllegalBusinessException("施工队长信息不存在");
        }
        // 2、指定的接单人必须是被配置到这个项目下的
        TUser teamMemberUserInfo = systemUserService.getUserInfoByUserId(String.valueOf(vo.getTeamMemberId()));
        if (ObjectUtil.isNull(teamMemberUserInfo)) {
            throw new BusinessException("您选择的施工队员不存在,请重新选择队员后再分单");
        }
        Long agentTeamMemberAuthId = projectServiceUserAuthService.getUserIdByProjectId(projectIdList.get(0), teamMemberUserInfo.getEasyRepairUserId(), Boolean.FALSE);
        if (ObjectUtil.isNull(agentTeamMemberAuthId)) {
            throw new BusinessException("您选择的施工队员未代理当前项目下的工单,请重新选择队员后再分单");
        }
        // 3、入参工单的行政区划代码必须被指定接单人负责的行政区划代码包含
        // 2024/7/19 先不校验这个,以后再加
///*        List<MyTeamWorkAreaDTO> workAreaList = projectServiceUserAuthService.getTeamMemberWorkArea(vo.getTeamMemberId());
//        if (CollectionUtil.isEmpty(workAreaList)) {
//            throw new Exception("您选择的施工队员未配置任何负责区域,请联系管理员配置负责区域后再分单");
//        }
//        List<Map<String, Object>> workOrderAreaInfoList = this.baseMapper.getAreaInfoByWorkOrderIdList(vo.getWorkOrderIdList());
//        for (Map<String, Object> workOrderAreaInfo : workOrderAreaInfoList) {
//            boolean flag = Boolean.TRUE;
//            for (MyTeamWorkAreaDTO workArea : workAreaList) {
//                String regionCodePrefix = XzqhUtils.getRegionCodePrefix(String.valueOf(workOrderAreaInfo.get("areaCode")), workArea.getAreaLevel());
//                if (workArea.getAreaCode().equals(regionCodePrefix)) {
//                    flag = Boolean.FALSE;
//                    break;
//                }
//            }
//            if (flag) {
//                throw new Exception("客户姓名为:【" + workOrderAreaInfo.get("contactName") + "】的工单所属区域不在当前施工队员的负责范围内,请重新选择后再分单");
//            }
//        }*/

        // 批量转单
        TransferOrderInstallBO transferOrderInstallBo = vo.convertToBo(TransferOrderInstallBO.class);
        transferOrderInstallBo.setWorkOrderIdList(vo.getWorkOrderIdList());
        transferOrderInstallBo.setMaintainId(teamMemberUserInfo.getCallCenterUserId());
        transferOrderInstallBo.setUserId(captainUserInfo.getCallCenterUserId());
        transferOrderInstallBo.setRemark("施工队长分单给:" + teamMemberUserInfo.getNickName());
        transferOrderInstallBo.setStatus(Integer.valueOf(WorkOrderStautsEnum._8.getKey()));
        this.batchTransferOrderInstall(transferOrderInstallBo);

        // 批量添加工单的操作记录
        workOrderRecordService.saveWorkOrderRecord(getWorkOrderRecords(transferOrderInstallBo));

        // 给接单队员发送新工单通知
        try {
            String body = "您的队长给您分配了" + vo.getWorkOrderIdList().size() + "个新的安装工单。";

            Map<String, String> sendParams = new HashMap<>();
            sendParams.put("workOrderType", "install");
            sendParams.put("workOrderId", String.valueOf(vo.getWorkOrderIdList().get(0)));
            sendParams.put("companyId", captainUserInfo.getCompanyId());
            sendMessageHandler.sendWorkOrderMessageToEasyRepair(null, body, Collections.singletonList(teamMemberUserInfo.getPhone()), sendParams);
        } catch (Exception e) {
            log.error("批量分单结束后发送通知消息失败,失败原因:{}", e.getMessage());
            e.printStackTrace();
        }
        return PageData.ok();
    }

    /**
     * 按行政区划分单
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void distributeWorkOrderByAreaCode(EasyRepairDistributeWorkOrderByAreaCodeVO vo) throws Exception {
        // 查询项目信息
        TProject projectInfo = tProjectService.getProjectByUuid(vo.getProjectUuid());
        if (ObjectUtil.isNull(projectInfo)) {
            throw new IllegalBusinessException("项目不存在");
        }

        // 获取userInfo - 因为这个接口是无鉴权接口,所以需要手动获取userInfo
        Long userId = projectServiceUserAuthService.getUserIdByProjectId(projectInfo.getId(), vo.getEasyRepairUserId(), Boolean.TRUE);
        TUser captainUserInfo = systemUserService.getUserInfoByUserId(String.valueOf(userId));
        if (ObjectUtil.isNull(captainUserInfo)) {
            throw new IllegalBusinessException("施工队长信息不存在");
        }

        // 查询相关安装工单列表
        List<WorkOrderInfo> workOrderList = this.getWorkOrderList(projectInfo.getId(), vo.getAreaCode());
        // 过滤出当前施工队长代理的安装工单
        List<Long> workOrderIdList = workOrderList.stream()
                .filter(n -> n.getMaintainId().equals(captainUserInfo.getCallCenterUserId()))
                .map(WorkOrderInfo::getId)
                .collect(Collectors.toList());
        if (CollectionUtil.isEmpty(workOrderIdList)) {
            log.info("按行政区划分单,没查询到任何工单信息!");
            return;
        }

        // 查询接单人信息
        TUser teamMemberUserInfo = systemUserService.getUserInfoByUserId(String.valueOf(vo.getTeamMemberId()));
        if (ObjectUtil.isNull(teamMemberUserInfo)) {
            throw new BusinessException("您选择的施工队员不存在,请重新选择队员后再分单");
        }
        // 检查安装人id
        if (ObjectUtil.isNull(teamMemberUserInfo.getCallCenterUserId())) {
            throw new IllegalBusinessException("转换安装人id异常,安装人信息:" + JSON.toJSONString(teamMemberUserInfo));
        }

        // 校验接单人负责行政区划
        List<String> serviceUserAllAreaCodes = projectServiceUserAuthService.getServiceUserAllAreaCodes(teamMemberUserInfo.getId(), projectInfo.getUuid());
        if (CollectionUtil.isEmpty(serviceUserAllAreaCodes)) {
            throw new BusinessException("您选择的施工队员未代理当前项目下的工单,请重新选择队员后再分单");
        }
        if (serviceUserAllAreaCodes.stream().noneMatch(n -> vo.getAreaCode().startsWith(XzqhUtils.getRegionCodePrefix(n)))) {
            throw new BusinessException("当前施工队员未配置当前行政区划,请确认后再分单");
        }

        // 批量转单
        TransferOrderInstallBO transferOrderInstallBo = vo.convertToBo(TransferOrderInstallBO.class);
        transferOrderInstallBo.setWorkOrderIdList(workOrderIdList);
        transferOrderInstallBo.setMaintainId(teamMemberUserInfo.getCallCenterUserId());
        transferOrderInstallBo.setUserId(captainUserInfo.getCallCenterUserId());
        transferOrderInstallBo.setRemark("施工队长分单给:" + teamMemberUserInfo.getNickName());
        transferOrderInstallBo.setStatus(Integer.valueOf(WorkOrderStautsEnum._8.getKey()));
        this.batchTransferOrderInstall(transferOrderInstallBo);
        // 批量添加工单的操作记录
        workOrderRecordService.saveWorkOrderRecord(getWorkOrderRecords(transferOrderInstallBo));

        // 给接单队员发送新工单通知
        try {
            String body = "您的队长给您分配了" + workOrderIdList.size() + "个新的安装工单。";

            Map<String, String> sendParams = new HashMap<>();
            sendParams.put("workOrderType", "install");
            sendParams.put("workOrderId", String.valueOf(workOrderIdList.get(0)));
            sendParams.put("companyId", vo.getOperateUserCompanyId());
            sendMessageHandler.sendWorkOrderMessageToEasyRepair(null, body, Collections.singletonList(teamMemberUserInfo.getPhone()), sendParams);
        } catch (Exception e) {
            log.error("批量分单结束后发送通知消息失败,失败原因:{}", e.getMessage());
            e.printStackTrace();
        }
    }

    /**
     * 校验接单人员身份
     */
    @Override
    public boolean validateServiceUserAuth(DistributeWorkOrderInstallBO bo) throws Exception {
        if (StrUtil.isBlank(bo.getMaintainId())) {
            throw new MissBusinessParameterException("接单人热链云用户id");
        }
        if (ObjectUtil.isNull(bo.getProjectId())) {
            throw new MissBusinessParameterException("工单所属项目id");
        }

        // 查询项目详情
        TProject projectDetail = tProjectService.getProjectDetail(bo.getProjectId());
        if (ObjectUtil.isNull(projectDetail)) {
            throw new IllegalBusinessException("工单所属项目不存在");
        }
        bo.setProjectUuid(projectDetail.getUuid());
        bo.setProjectName(projectDetail.getProjectName());

        // 查询是否属于团队
        boolean belongToTeam = projectServiceUserAuthService.validateBelongToTeam(Long.valueOf(bo.getMaintainId()), projectDetail.getUuid());
        if (!belongToTeam) {
            log.info("接单人不属于任何施工队,可以接单");
            return false;
        }
        // 查询是否为当前项目的队长
        boolean isCaptain = projectServiceUserAuthService.validateHeadAuth(Long.valueOf(bo.getMaintainId()), projectDetail.getUuid());
        if (!isCaptain) {
            throw new BusinessException("当前接单人是施工队员,派单失败!");
        }

        log.info("当前接单人是施工队长,需要校验行政区划代码");
        return true;
    }

    /**
     * 审核功能
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public PageData workOrderReview(WorkOrderReviewVo vo) {
        try {
            List<String> workOrderIdList = vo.getWorkOrderIdList();
            List<String> auditCommentsList = vo.getAuditCommentsList();
            List<Integer> auditedList = vo.getAuditedList();
            for (int i = 0; i < workOrderIdList.size(); i++) {
                if (auditCommentsList.isEmpty()) {
                    //如果是批量的，意见不填就为空
                    workOrderDataMapper.workOrderReview(workOrderIdList.get(i), auditedList.get(i), "", vo.getOperateUserCompanyId());
                    AgentPushCtceDataVO agentPushCtceDataVO = new AgentPushCtceDataVO();
                    agentPushCtceDataVO.setWorkOrderId(Long.parseLong(workOrderIdList.get(i)));
                    agentPushCtceDataVO.setOrderCreateUserId(vo.getOperateUserId().toString());
                    agentPushCtceDataVO.setOrderBelongCompanyId(vo.getOperateUserCompanyId());
                    agentPushCtceDataVO.setUserInfo(vo.getUserInfo());
                    agentPushCtceDataVO.setOperateUserCompanyType(vo.getOperateUserCompanyType());
                    agentPushCtceDataVO.setOperateUserCallCenterCompanyId(vo.getOperateUserCallCenterCompanyId());
                    agentPushCtceService.agentPushCtceData(agentPushCtceDataVO);
                } else {
                    workOrderDataMapper.workOrderReview(workOrderIdList.get(i), auditedList.get(i), auditCommentsList.get(i), vo.getOperateUserCompanyId());
                    AgentPushCtceDataVO agentPushCtceDataVO = new AgentPushCtceDataVO();
                    agentPushCtceDataVO.setWorkOrderId(Long.parseLong(workOrderIdList.get(i)));
                    agentPushCtceDataVO.setOrderCreateUserId(vo.getOperateUserId().toString());
                    agentPushCtceDataVO.setOrderBelongCompanyId(vo.getOperateUserCompanyId());
                    agentPushCtceDataVO.setUserInfo(vo.getUserInfo());
                    agentPushCtceDataVO.setOperateUserCompanyType(vo.getOperateUserCompanyType());
                    agentPushCtceDataVO.setOperateUserCallCenterCompanyId(vo.getOperateUserCallCenterCompanyId());
                    agentPushCtceService.agentPushCtceData(agentPushCtceDataVO);
                }
            }
        } catch (Exception e) {
            throw new BusinessException(e.getMessage());
        }
        return PageData.ok("更改成功");
    }

    /**
     * 撤销安装工单
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void cancelWorkOrders(CancelWorkOrdersBO bo) throws Exception {
        List<Long> workOrderIdList = bo.getWorkOrderIdList();

        if (CollectionUtil.isEmpty(workOrderIdList)) {
            throw new MissBusinessParameterException("workOrderIdList must not empty");
        }

        // 校验是否有已完成的工单
        QueryWrapper<WorkOrderInfo> checkWrapper = new QueryWrapper<>();
        checkWrapper.in("id", workOrderIdList);
        checkWrapper.in("status", WorkOrderStautsEnum.getStatusList(true));
        checkWrapper.eq("is_delete", DeleteEnum._0.getKey());
        Integer completeWorkOrderCount = this.baseMapper.selectCount(checkWrapper);
        if (completeWorkOrderCount > 0) {
            throw new BusinessException("当前选择的安装工单包含已完成的工单,撤销失败!");
        }

        // 批量删除安装工单 - 逻辑删除
        QueryWrapper<WorkOrderInfo> delWrapper = new QueryWrapper<>();
        delWrapper.in("id", workOrderIdList);
        delWrapper.eq("is_delete", DeleteEnum._0.getKey());

        WorkOrderInfo workOrderInfo = new WorkOrderInfo();
        workOrderInfo.setIsDelete(DeleteEnum._1.getKey());

        int delRows = this.baseMapper.update(workOrderInfo, delWrapper);
        if (delRows <= 0) {
            throw new IllegalBusinessException("撤销安装工单失败");
        }

        // 恢复销售订单和系统单的派单状态
        Map<String, List<Long>> saleOrderIdMap = crmFlowTableRelationshipService.getSaleOrderIdMap(workOrderIdList);

        CancelSaleOrderBO cancelSaleOrderBO = new CancelSaleOrderBO();
        BeanUtils.copyProperties(bo, cancelSaleOrderBO);
        cancelSaleOrderBO.setPriceMasterIdList(saleOrderIdMap.get("priceMasterIdList"));
        cancelSaleOrderBO.setSaleOrderIdList(saleOrderIdMap.get("saleOrderIdList"));
        saleOrderInfoService.cancelSaleOrder(cancelSaleOrderBO);

        // 批量删除设备 - 逻辑删除
        equipmentService.delEquipmentInfoByWorkOrderId(workOrderIdList, bo.getOperateDate(), bo.getOperateUserId());

        // 批量删除工单、商机关系数据 - 逻辑删除
        crmFlowTableRelationshipService.batchDeleteCrmFlowData(workOrderIdList, bo.getOperateDate(), bo.getOperateUserId());

        // 批量新增工单删除操作记录
        List<WorkOrderRecord> workOrderRecordList = new ArrayList<>();
        for (Long workOrderId : bo.getWorkOrderIdList()) {
            WorkOrderRecord workOrderRecord = new WorkOrderRecord();
            workOrderRecord.setWorkOrderId(workOrderId);
            workOrderRecord.setDesc("撤销安装工单");
            workOrderRecord.setUserId(bo.getOperateUserId());
            workOrderRecord.setStatus(Integer.valueOf(WorkOrderStautsEnum._4.getKey()));
            workOrderRecord.setIsDelete(DeleteEnum._0.getKey());
            workOrderRecord.setGmtCreate(bo.getOperateTimeStamp());
            workOrderRecord.setGmtModified(bo.getOperateTimeStamp());

            workOrderRecordList.add(workOrderRecord);

            // 修改分单记录 - 修改为分单记录无效
            workOrderRecordService.updateWorkOrderRecord(workOrderId);
        }
        workOrderRecordService.saveWorkOrderRecord(workOrderRecordList);

        // 撤销了哪些人的工单，就给哪些人发消息
        try {
            // 根据工单id查询它们的处理人id(热链云用户id)
            Map<Long, String> map = this.queryWorkOrderMaintainIdByWorkOrderId(workOrderIdList);
            // 按用户id统计他们被撤销工单的数量
            Map<String, Integer> map1 = new HashMap<>();
            for (Long workOrderId : map.keySet()) {
                String userId = map.get(workOrderId);
                map1.put(userId, ObjectUtil.isNull(map1.get(userId)) ? 1 : map1.get(userId)+1);
            }
            // 给这些用户发送撤销工单通知
            String title = "工单已被撤销";
            for (String userId : map1.keySet()) {
                String body = "您有" + map1.get(userId) + "个工单已被撤销。";
                sendMessageHandler.sendWorkOrderMessageToEasyRepair(title, body, systemUserService.getUserPhoneById(userId), null);
            }
        } catch (Exception e) {
            log.error("批量撤销工单结束后发送通知消息失败,失败原因:{}", e.getMessage());
            e.printStackTrace();
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void cancelWorkOrdersByAreaCode(CancelWorkOrdersByAreaCodeBO bo) throws Exception {
        // 校验参数
        if (ObjectUtil.isNull(bo.getProjectId())) {
            throw new MissBusinessParameterException("projectId must not null");
        }
        if (StrUtil.isBlank(bo.getAreaCode())) {
            throw new MissBusinessParameterException("areaCode must not empty");
        }
        if (CollectionUtil.isEmpty(bo.getWorkOrderStatusSet())) {
            throw new MissBusinessParameterException("workOrderStatusSet must not empty");
        }

        // 查询当前项目所在的行政区划的全部工单
        List<WorkOrderInfo> workOrderList = this.getWorkOrderList(bo.getProjectId(), bo.getAreaCode());

        // 记录可以撤销的工单id
        List<Long> workOrderIds = new ArrayList<>();

        // 过滤撤销状态范围内的工单
        if (CollectionUtil.isNotEmpty(workOrderList)) {
            // 入参的工单状态
            Set<Integer> workOrderStatus = bo.getWorkOrderStatusSet().stream()
                    .filter(n -> n.startsWith(CancelWorkOrdersStatusEnum.ORDER_STATUS_PREFIX.getKey()))
                    .map(n -> Integer.valueOf(n.substring(CancelWorkOrdersStatusEnum.ORDER_STATUS_PREFIX.getKey().length())))
                    .collect(Collectors.toSet());
            // 入参的接单状态
            Set<Integer> serviceStatus = bo.getWorkOrderStatusSet().stream()
                    .filter(n -> n.startsWith(CancelWorkOrdersStatusEnum.SERVICE_STATUS_PREFIX.getKey()))
                    .map(n -> Integer.valueOf(n.substring(CancelWorkOrdersStatusEnum.SERVICE_STATUS_PREFIX.getKey().length())))
                    .collect(Collectors.toSet());
            // 取出需要撤销的工单id列表
            workOrderIds = workOrderList.stream()
                    .filter(workOrderInfo -> {
                        if (ObjectUtil.isNull(workOrderInfo.getStatus()) || ObjectUtil.isNull(workOrderInfo.getMaintainStatus())) {
                            return false;
                        }

                        // 工单状态符合入参
                        boolean workOrderStatusFlag = workOrderStatus.contains(workOrderInfo.getStatus());
                        // 工单状态=处理中 && 接单状态符合入参
                        boolean serviceStatusFlag = Integer.valueOf(WorkOrderStautsEnum._2.getKey()).equals(workOrderInfo.getStatus())
                                && serviceStatus.contains(workOrderInfo.getMaintainStatus());

                        return workOrderStatusFlag || serviceStatusFlag;
                    })
                    .map(WorkOrderInfo::getId)
                    .collect(Collectors.toList());
        }

        // 记录是否撤销成功
        boolean cancelSuccess = true;
        // 记录撤销失败说明
        String faultMessage = StrUtil.EMPTY;

        // 调用上面的批量撤销工单功能
        try {
            if (CollectionUtil.isEmpty(workOrderIds)) {
                log.info("未查询到任何符合条件的工单,不用撤销");
                // 此处继续向下执行是为了获取抛出的异常
            }
            CancelWorkOrdersBO cancelWorkOrdersBO = new CancelWorkOrdersBO();
            cancelWorkOrdersBO.setWorkOrderIdList(workOrderIds);
            this.cancelWorkOrders(cancelWorkOrdersBO);
        } catch (Exception e) {
            cancelSuccess = false;
            faultMessage = e.getMessage();
            log.error("批量撤销安装工单失败!失败原因:{}", e.getMessage());
        } finally {
            final boolean finalFlag = cancelSuccess;
            final String finalFaultMessage = faultMessage;
            // 新增批量撤销工单记录
            InsertCancelRecordBO insertCancelRecordBO = new InsertCancelRecordBO();
            BeanUtils.copyProperties(bo, insertCancelRecordBO);
            insertCancelRecordBO.setBatchNumber(bo.getOperateTimeStamp());
            insertCancelRecordBO.setWorkOrderCount((long) workOrderIds.size());
            insertCancelRecordBO.setSuccessCount(cancelSuccess ? (long) workOrderIds.size() : 0L);
            insertCancelRecordBO.setFaultCount( !cancelSuccess ? (long) workOrderIds.size() : 0L);
            insertCancelRecordBO.setInsertCancelDetailBOList(workOrderIds.stream().map(n -> {
                WorkOrderInfo workOrderInfo = workOrderList.stream().filter(m -> n.equals(m.getId())).findFirst().orElse(null);
                if (ObjectUtil.isNull(workOrderInfo)) {
                    return null;
                }
                InsertCancelDetailBO insertCancelDetailBO = new InsertCancelDetailBO();
                BeanUtils.copyProperties(bo, insertCancelDetailBO);
                insertCancelDetailBO.setWorkOrderId(workOrderInfo.getId());
                insertCancelDetailBO.setWorkOrderName(workOrderInfo.getWorkOrderName());
                insertCancelDetailBO.setCancelSuccess(finalFlag);
                insertCancelDetailBO.setFaultMessage(finalFaultMessage);
                return insertCancelDetailBO;
            }).collect(Collectors.toList()));
            workOrderCancelRecordService.insertCancelRecord(insertCancelRecordBO);
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void captainCancelWorkOrders(CaptainCancelWorkOrdersBO bo) throws Exception {
        if (CollectionUtil.isEmpty(bo.getWorkOrderIdList())) {
            throw new MissBusinessParameterException("workOrderIdList must not empty");
        }

        // 准备一个map接收队员的长效管护用户id和撤回工单条数
        Map<Long, Integer> map = new HashMap<>();

        // 以单条转单的方式撤回工单 - 由于需要给每一个工单确认由谁转给谁，所以这里直接循环执行单条撤回比较好
        for (Long workOrderId : bo.getWorkOrderIdList()) {
            // 查询工单有效分单记录
            List<WorkOrderRecordListDto> workOrderRecordList = workOrderRecordService.getWorkOrderRecordList(workOrderId);

            WorkOrderRecordListDto recordDto = workOrderRecordList.stream()
                    .filter(n -> Integer.valueOf(WorkOrderStautsEnum._8.getKey()).equals(n.getStatus()) && n.getEffectiveRecord().equals(Boolean.TRUE))
                    .findFirst()
                    .orElse(null);

            if (ObjectUtil.isNull(recordDto)) {
                log.error("未查询到工单有效分单记录,撤销工单失败");
                continue;
            }

            CcUser ccUser = ccUserService.getCcUser(recordDto.getUserId());

            TransferOrderInstallBO transferOrderInstallBO = new TransferOrderInstallBO();
            transferOrderInstallBO.setWorkOrderIdList(Collections.singletonList(workOrderId));
            transferOrderInstallBO.setLongitude(bo.getLongitude());
            transferOrderInstallBO.setLatitude(bo.getLatitude());
            transferOrderInstallBO.setMaintainId(ccUser.getId());
            transferOrderInstallBO.setMaintainName(ccUser.getName());
            transferOrderInstallBO.setRemark("施工队长撤销派单");
            transferOrderInstallBO.setStatus(Integer.valueOf(WorkOrderStautsEnum._9.getKey()));
            transferOrderInstallBO.setUserId(recordDto.getMaintainId());
            this.batchTransferOrderInstall(transferOrderInstallBO);

            // 批量添加工单的操作记录
            workOrderRecordService.saveWorkOrderRecord(getWorkOrderRecords(transferOrderInstallBO));

            // 修改分单记录 - 修改为分单记录无效
            workOrderRecordService.updateWorkOrderRecord(workOrderId);

            map.put(recordDto.getMaintainId(), map.containsKey(recordDto.getMaintainId()) ? map.get(recordDto.getMaintainId()) + 1 : 1);
        }

        // 撤销了哪些人的工单，就给哪些人发消息
        try {
            String title = "工单已被撤销";
            for (Long callCenterUserId : map.keySet()) {
                String body = "您有" + map.get(callCenterUserId) + "个工单已被撤销。";

                TUser userInfo = systemUserService.getUserInfoByCallCenterUserId(String.valueOf(callCenterUserId));
                if (ObjectUtil.isNull(userInfo)) {
                    log.error("根据长效管护获取热链云用户信息失败!");
                    continue;
                }
                sendMessageHandler.sendWorkOrderMessageToEasyRepair(title, body, Collections.singletonList(userInfo.getPhone()), null);
            }
        } catch (Exception e) {
            log.error("批量撤销工单结束后发送通知消息失败,失败原因:{}", e.getMessage());
            e.printStackTrace();
        }
    }

    @Override
    public String saveWorkOrder(WorkOrderBO workOrderBO) throws Exception {
        return workOrderServiceStrategyFactory.getCustomerBuilderService(workOrderBO.getType()).saveWorkOrder(workOrderBO);
    }

    @Override
    public Long createRepairWorkOrder(WorkOrderBO bo) throws Exception {

        //生成一个随机签到码
        String verificationCode = MathUtils.randomDigitNumber(4);
        bo.setVerificationCode(verificationCode);
        // 组装WorkOrderInfo实体类
        WorkOrderInfo info = new WorkOrderInfo();
        info.setAppealCategory(bo.getAppealCategory());
        info.setEvaluation(bo.getEvaluation());
        info.setAddress(bo.getAddress());
        info.setCompanyId(Long.parseLong(bo.getUserInfo().getCallCenterCompanyId()));
        info.setHouseId(bo.getHouseId());
        info.setClienteleId(0L);
        if(ObjectUtil.isNotEmpty(bo.getHandleMode())){
            info.setHandleMode(bo.getHandleMode());
        }else {
           info.setHandleMode(5);
        }
        info.setUserId(bo.getUserInfo().getCallCenterUserId());
        info.setContact(bo.getCustomerName());
        info.setContactPhone(bo.getPhone());
        info.setWorkTypeId(Long.parseLong(String.valueOf(bo.getWorkTypeId())));
        info.setEmergencyDegreeId(bo.getEmergencyDegreeId());
       //算距离
            TUser installUserInfo = systemUserService.getUserInfoByUserId(bo.getMaintainId());
        if (ObjectUtil.isNull(installUserInfo) || ObjectUtil.isNull(installUserInfo.getCallCenterUserId())) {
            throw new IllegalBusinessException("转换人业务支持员id异常,业务支持员信息:" + JSON.toJSONString(installUserInfo));
        }
        if (!bo.getCompanyId().equals(bo.getOperateUserCompanyId())) {
            info.setMaintainId(null);
        }else{
            info.setMaintainId(installUserInfo.getCallCenterUserId());
        }

            /*Integer distance =0;
            if(ObjectUtil.isNotEmpty(installUserInfo.getLatitude())) {
                distance = MapUtils.getDistanceBetweenOriginNDestination(installUserInfo.getLatitude().toString(), installUserInfo.getLongitude().toString(), bo.getLatitude().toString(), bo.getLongitude().toString());
            }else {
                Company company = businessCompanyService.getCompany(bo.getCompanyId());
                 distance = MapUtils.getDistanceBetweenOriginNDestination(company.getLatitude().toString(), company.getLongitude().toString(), company.getLatitude().toString(), company.getLongitude().toString());
            }
            if (distance != null && distance > 0) {
                info.setDistance(distance / 1000);
            }
            info.setDistance(bo.getDistance());//算师傅的距离和设备的距离*/

        info.setErroCode(bo.getErroCode());
        info.setSbSfzb(bo.getSb_sfzb());
        info.setVerificationCode(bo.getVerificationCode());
        info.setLongitude(bo.getLongitude());
        info.setLatitude(bo.getLatitude());
        info.setCustomerId(bo.getClienteleId());
        info.setCustomerHouseId(bo.getHouseId());
        info.setHouseNumber(bo.getHouseNumber());
        info.setAudited(Integer.parseInt(AuditedEnum._0.getKey()));
        info.setSystemType(1);
        info.setWorkOrderName(bo.getCustomerName() + "的维修工单");
        info.setEquipmentIds(bo.getEquipmentIds());
        if (ObjectUtil.isNotNull(bo.getHandleMode())) {
            info.setHandleMode(bo.getHandleMode());
            info.setHandleId(bo.getHandleId());
        }
        info.setAddress(bo.getAddress());
        info.setXzqhdm(bo.getXzqhdm());
        info.setEquipmentCompanyId(Long.parseLong(bo.getUserInfo().getCallCenterCompanyId()));
        info.setDesc(bo.getDesc());
        info.setMaintainStatus(Integer.parseInt(MaintainWorkOrderStautsEnum._3.getKey()));
        info.setStatus(Integer.parseInt(WorkOrderStautsEnum._2.getKey()));
        info.setIsDelete(0);
        info.setGmtCreate(System.currentTimeMillis());
        info.setGmtModified(bo.getOperateTimeStamp());
        info.setBaseDistance(new BigDecimal(10));

        info.setPricePerKM(new BigDecimal(3));//默认3块1公里
        if ("01".equals(bo.getSb_sfzb())) {
            info.setCharged(0);
        } else {
            info.setCharged(1);
        }
        int result = workOrderDataMapper.insert(info);
        bo.setWorkOrderId(info.getId());
        int result1 = 0;
        if (!bo.getCompanyId().equals(bo.getOperateUserCompanyId())) {
            info.setMaintainId(installUserInfo.getCallCenterUserId());
            info.setPWorkOrderId(info.getId());
            info.setMaintainStatus(Integer.parseInt(MaintainWorkOrderStautsEnum._3.getKey()));
            info.setStatus(Integer.parseInt(WorkOrderStautsEnum._2.getKey()));
            Company company = businessCompanyService.getCompany(bo.getCompanyId());
            info.setCompanyId(Long.parseLong(company.getCcCompanyId()));
            info.setUserId(bo.getUserInfo().getCallCenterUserId());
            result1 = workOrderDataMapper.insert(info);
            bo.setPWorkOrderId(info.getId());
        }
        if (0 >= result && 0 >= result1) {
            throw new BusinessException("保存维修工单失败!");
        }
        return bo.getWorkOrderId();
    }

    @Override
    public Long createConsultWorkOrder(WorkOrderBO workOrderBO) {
        WorkOrderInfo info = new WorkOrderInfo();
        info.setCompanyId(Long.parseLong(workOrderBO.getUserInfo().getCallCenterCompanyId()));
        info.setClienteleId(0L);
        info.setUserId(workOrderBO.getUserInfo().getCallCenterUserId());//长效管护id
        info.setHandleMode(0);
        info.setType(3);
        info.setLatitude(workOrderBO.getLatitude());
        info.setLongitude(workOrderBO.getLongitude());
        info.setContact(workOrderBO.getCustomerName());
        info.setContactPhone(workOrderBO.getPhone());
        info.setXzqhdm(workOrderBO.getXzqhdm());
        info.setAddress(workOrderBO.getAddress());
        info.setDesc(workOrderBO.getAppealContent());
        info.setConsultType(workOrderBO.getConsultType());
        info.setStatus(Integer.parseInt(WorkOrderStautsEnum._3.getKey()));
        info.setIsDelete(DeleteEnum._0.getKey());
        info.setGmtCreate(workOrderBO.getOperateTimeStamp());
        info.setGmtModified(workOrderBO.getOperateTimeStamp());
        info.setCustomerId(workOrderBO.getClienteleId());
        info.setWorkOrderName(workOrderBO.getCustomerName() + "的咨询工单");
        info.setHandleMode(5);
        info.setAudited(1);           // 默认审核完成
        info.setTimeoutType(0);     // 超时类型为0不超时
        info.setMaintainId(workOrderBO.getUserInfo().getCallCenterUserId());    // 咨询工单处理人设置为自己
        info.setMaintainStatus(Integer.parseInt(MaintainWorkOrderStautsEnum._2.getKey()));   // 咨询工单处理人状态为完成
        info.setSystemType(1);
        int result = workOrderDataMapper.insert(info);
        if (0 >= result) {
            throw new BusinessException("保存咨询工单失败!");
        }
        return info.getId();
    }

    @Override
    public Page<SaveWorkOrderByQueryDto> queryCustomerEquipmentList(SaveWorkOrderQueryVo vo) throws Exception {
        if (ObjectUtil.isEmpty(vo.getEquipmentCompanyId())) {
            vo.setEquipmentCompanyId(vo.getOperateUserCompanyId());
        }
        //查询类型
        vo.setCompanyType(businessCompanyService.getCompany(vo.getEquipmentCompanyId()).getCompanytype());
        Page<SaveWorkOrderByQueryDto> page = new Page<>(vo.getPageid(), vo.getPagesize());
        List<SaveWorkOrderByQueryDto> list = queryCustomerEquipmentMapper.queryCustomerEquipmentList(page, vo);
        return page.setRecords(list);
    }

    @Override
    public GetDeviceDto getDevice(GetDevice vo) {
        //查询类型
        GetDeviceDto getDeviceDto = queryCustomerEquipmentMapper.getDevice(vo);
        Date warrantyExpiryDate = getDeviceDto.getWarrantyExpiryDate();
        if (warrantyExpiryDate == null) {
            getDeviceDto.setIsWarrantyExpiry(null);
        } else getDeviceDto.setIsWarrantyExpiry(warrantyExpiryDate.compareTo(new Date()) < getDeviceDto.getZbq());
        return getDeviceDto;
    }

    // 校验接单人是否可以接单
    private void validateInstallUserAuth(DistributeWorkOrderInstallBO bo, String areaCode) throws Exception {
        if (StrUtil.isBlank(bo.getMaintainId())) {
            throw new MissBusinessParameterException("接单人热链云用户id");
        }
        if (ObjectUtil.isNull(bo.getProjectId())) {
            throw new MissBusinessParameterException("工单所属项目id");
        }
        if (StrUtil.isBlank(areaCode)) {
            throw new MissBusinessParameterException("行政区划代码");
        }

        // 是否做过身份校验,如果没做过 - 那么就重新做接单人身份校验
        Boolean isCaptain = bo.getIsCaptain();
        if (ObjectUtil.isNull(isCaptain)) {
            isCaptain = this.validateServiceUserAuth(bo);
        }
        // 如果不是队长就直接派单
        if (!isCaptain) {
            return;
        }
        // 如果是队长就做服务行政区划代码校验
        // 查询工头负责的全部行政区划代码
        List<String> serviceUserAllAreaCodes = projectServiceUserAuthService.getServiceUserAllAreaCodes(Long.valueOf(bo.getMaintainId()), bo.getProjectUuid());
        if (CollectionUtil.isEmpty(serviceUserAllAreaCodes)
                || serviceUserAllAreaCodes.stream().noneMatch(n -> areaCode.startsWith(XzqhUtils.getRegionCodePrefix(n)))) {
            throw new BusinessException("当前工单不在接单人的负责行政区划内");
        }
    }

    //更新业务支持人员坐标
    private void updateUserCoordinate(Long userId, BigDecimal longitude, BigDecimal latitude, String phone) {
        //封装数据
        SaveCcUserVo saveCcUserVo = new SaveCcUserVo();
        saveCcUserVo.setUserId(userId);
        saveCcUserVo.setLongitude(longitude);
        saveCcUserVo.setLatitude(latitude);
        saveCcUserVo.setPhone(phone);
        ccUserService.updateUserCoordinate(saveCcUserVo);
    }

    // 组装批量转单记录参数
    private List<WorkOrderRecord> getWorkOrderRecords(TransferOrderInstallBO bo) {
        List<WorkOrderRecord> workOrderRecordList = new ArrayList<>();
        for (Long workOrderId : bo.getWorkOrderIdList()) {
            WorkOrderRecord workOrderRecord = new WorkOrderRecord();
            workOrderRecord.setWorkOrderId(workOrderId);
            workOrderRecord.setDesc(bo.getRemark());
            workOrderRecord.setMaintainId(bo.getMaintainId());
            workOrderRecord.setStatus(bo.getStatus());
            workOrderRecord.setIsDelete(DeleteEnum._0.getKey());
            workOrderRecord.setGmtCreate(bo.getOperateTimeStamp());
            workOrderRecord.setGmtModified(bo.getOperateTimeStamp());
            workOrderRecord.setLatitude(bo.getLatitude());
            workOrderRecord.setLongitude(bo.getLongitude());
            workOrderRecord.setUserId(bo.getUserId());
            if (ObjectUtil.isNotNull(bo.getStatus()) && WorkOrderStautsEnum._8.getKey().equals(String.valueOf(bo.getStatus()))) {
                workOrderRecord.setEffectiveRecord(Boolean.TRUE);
            }

            workOrderRecordList.add(workOrderRecord);
        }
        return workOrderRecordList;
    }

    // 设置工单信息字段
    private void setWorkOrderInfoFields(GetWorkOrderInstallDetailVO vo, WorkOrderInstallInfoDTO workOrderInfo) {
        Company company = businessCompanyService.getCompanyByCallCenterCompanyId(workOrderInfo.getCallCenterCompanyId());
        workOrderInfo.setOrderCreateSource(ObjectUtil.isNotNull(company) ? company.getCompanyname() : StrUtil.EMPTY);
        workOrderInfo.setInstallStateName(tParamService.getNameByParamTypeAndValue(DictTypeEnum.INSTALL_STATE.getParamType(), String.valueOf(workOrderInfo.getInstallState())));
        workOrderInfo.setProcureSourceName(tParamService.getNameByParamTypeAndValue(DictTypeEnum.PROCURE_SOURCE.getParamType(), String.valueOf(workOrderInfo.getProcureSource())));
        // 处理安装日期
        String installDateStr = StrUtil.EMPTY;
        if (ObjectUtil.isNotNull(workOrderInfo.getInstallDate())) {
            installDateStr = new SimpleDateFormat("yyyy-MM-dd").format(workOrderInfo.getInstallDate());
        }
        workOrderInfo.setInstallDateStr(installDateStr);
        workOrderInfo.setInstallOrderEquipments(gGoodsService.queryInstallOrderEquipmentInfo(workOrderInfo.getId()));

        // 设置当前工单是否可以操作
        workOrderInfo.setNeedToOperate(true);
        try {
            TUser userInfoByUserId = systemUserService.getUserInfoByUserId(String.valueOf(vo.getOperateUserId()));
            List<String> callCenterUserIdList = systemUserService.getCallCenterUserIdListByEasyRepairUserId(userInfoByUserId.getEasyRepairUserId());
            workOrderInfo.setNeedToOperate(callCenterUserIdList.contains(String.valueOf(workOrderInfo.getMaintainId())));
            // 如果工单不属于当前登录人 && 工单未完成 - 可以撤销
            if (!workOrderInfo.getNeedToOperate() && !WorkOrderStautsEnum.getIsComplete(workOrderInfo.getOrderStatus())) {
                workOrderInfo.setCanCancel(true);
            }
        } catch (Exception e) {
            log.error("设置安装工单可操作标识字段失败");
        }
    }

    // 组装易修分单界面相关返回值
    private List<GetWorkOrderInstallPageDTO> getMyTeamWorkOrderInstallRecords(List<WorkOrderInfo> workOrderInfoList, Long easyRepairUserId) {
        List<GetWorkOrderInstallPageDTO> records = new ArrayList<>();
        if (CollectionUtil.isEmpty(workOrderInfoList)) {
            return records;
        }

        // 查询所有公司，方便后续取值
        List<CcCompany> allCompanys = ccCompanyService.selectList();
        Map<Long, CcCompany> companyMap = allCompanys.stream().collect(Collectors.toMap(CcCompany::getId, ccCompany -> ccCompany));

        // 查询当前调接口的用户对应哪些热链云账号
        List<String> callCenterUserIdListByEasyRepairUserId = systemUserService.getCallCenterUserIdListByEasyRepairUserId(easyRepairUserId);

        // 查询当前工单结果集对应的项目信息
        Set<Long> workOrderIdList = workOrderInfoList.stream().map(WorkOrderInfo::getId).collect(Collectors.toSet());
        Map<Long, Long> workOrderProjectIdMap = crmFlowTableRelationshipService.getWorkOrderProjectIdMap(workOrderIdList);

        Map<Long, TProject> projectMap = new HashMap<>();
        for (WorkOrderInfo workOrderInfo : workOrderInfoList) {
            GetWorkOrderInstallPageDTO item = new GetWorkOrderInstallPageDTO();
            item.setWorkOrderId(workOrderInfo.getId());
            item.setWorkOrderCreateTime(new Date(workOrderInfo.getGmtCreate()));
            item.setContactName(workOrderInfo.getContact());
            item.setContactPhone(workOrderInfo.getContactPhone());
            item.setCompanyId(String.valueOf(workOrderInfo.getCompanyId()));
            item.setMaintainId(String.valueOf(workOrderInfo.getMaintainId()));
            item.setProjectId(String.valueOf(workOrderProjectIdMap.get(workOrderInfo.getId())));
            item.setAreaCode(workOrderInfo.getXzqhdm());

            // 获取项目信息
            TProject projectInfo = projectMap.get(workOrderProjectIdMap.get(workOrderInfo.getId()));
            if (ObjectUtil.isNull(projectInfo)) {
                projectInfo = tProjectService.getProjectDetail(workOrderProjectIdMap.get(workOrderInfo.getId()));
                projectMap.put(workOrderInfo.getId(), projectInfo);
            }
            item.setOrderCreateSource(companyMap.get(Long.valueOf(item.getCompanyId())) == null ? "" : companyMap.get(Long.valueOf(item.getCompanyId())).getName());
            item.setDistributeStatusName(StrUtil.isNotBlank(item.getMaintainId()) && callCenterUserIdListByEasyRepairUserId.stream().anyMatch(n -> item.getMaintainId().equals(n)) ? "未分单" : "已分单");
            item.setAreaName(xzqhService.getAreaName(item.getAreaCode()));
            item.setProjectName(ObjectUtil.isNull(projectInfo) ? "未知项目" : projectInfo.getProjectName());
            item.setProjectUuid(projectInfo.getUuid());
            item.setInstallAddress(workOrderInfo.getAddress());
            records.add(item);
        }
        return records;
    }

    // 查询我的项目的工单前置校验
    private void validate(GetTeamWorkOrderInstallPageBO bo) throws Exception {
        if (ObjectUtil.isNull(bo.getEasyRepairUserId())) {
            throw new MissBusinessParameterException("easyRepairUserId must not be null");
        }
        if (StrUtil.isBlank(bo.getProjectUuid())) {
            throw new MissBusinessParameterException("projectUuid must not empty");
        }
        if (!projectServiceUserAuthService.validateHeadAuth(bo.getEasyRepairUserId())) {
            throw new BusinessException("当前用户没有操作权限！");
        }
    }

    // 查询行政区划编码结果集
    private Set<String> getAllAreaCode(GetTeamWorkOrderInstallPageBO bo, Long captainAgentUserId) throws Exception {
        // 查询施工队长的行政区划代码
        if (ObjectUtil.isNull(captainAgentUserId)) {
            throw new MissBusinessParameterException("captainAgentUserId must not null");
        }
        List<String> captainAreaCodeList = projectServiceUserAuthService.getServiceUserAllAreaCodes(captainAgentUserId, bo.getProjectUuid());

        // 查询施工队员的行政区划代码
        List<String> teamMemberAreaCodeList = new ArrayList<>();
        if (ObjectUtil.isNotNull(bo.getTeamMemberId())) {
            teamMemberAreaCodeList = projectServiceUserAuthService.getServiceUserAllAreaCodes(bo.getTeamMemberId(), bo.getProjectUuid());
            if (CollectionUtil.isEmpty(teamMemberAreaCodeList)) {
                throw new BusinessException("该人员未设置负责区域");
            }
        }

        // 处理传入了行政区划代码
        List<String> paramAreaCodeList = new ArrayList<>();
        if (StrUtil.isNotBlank(bo.getAreaCode())) {
            List<SystemXzqh> xzqhList = xzqhService.getListByPrefix(XzqhUtils.getRegionCodePrefix(bo.getAreaCode()));
            if (CollectionUtil.isNotEmpty(xzqhList)) {
                paramAreaCodeList = xzqhList.stream().map(SystemXzqh::getXzqhdm).collect(Collectors.toList());
            }
        }

        // 取行政区划代码交集
        return xzqhService.handleAreaCodeList(true, true, captainAreaCodeList, teamMemberAreaCodeList, paramAreaCodeList);

    }

    // 处理门牌号模糊查询
    private List<Long> handleHouseNumber(String houseNumber) {
        // 处理门牌号模糊查询
        if (StrUtil.isNotBlank(houseNumber)) {
            return customerHouseService.getHouseIdListByHouseNumber(houseNumber);
        } else {
            return Collections.emptyList();
        }
    }

    // 校验拒单参数
    private void validate(RejectionOrderInstallVo vo) {
        // 校验入参是否合法
        if (ObjectUtil.isNull(vo.getWorkOrderId())) {
            throw new MissBusinessParameterException("工单ID");
        }
        if (ObjectUtil.isNull(vo.getDesc())) {
            throw new MissBusinessParameterException("拒单描述");
        }
        // 查询工单详情
        WorkOrderInfo workOrderInfo = this.getWorkOrderInfo(vo.getWorkOrderId());
        if (ObjectUtil.isNull(workOrderInfo)) {
            throw new IllegalBusinessException("安装工单不存在");
        }
        // 查询工单关联的项目id
        Long projectId = crmFlowTableRelationshipService.getProjectId(workOrderInfo.getId());
        // 查询项目详情
        TProject projectDetail = tProjectService.getProjectDetail(projectId);
        if (ObjectUtil.isNull(projectDetail)) {
            throw new IllegalBusinessException("工单关联的项目不存在!");
        }
        vo.setProjectUuid(projectDetail.getUuid());
    }


    @Override
    public PageData getRepairWorkOrderPage(GetWorkOrderRepairPageVO vo) throws Exception {
        if (ObjectUtil.isEmpty(vo.getType())) {
            vo.setType(1);
        }
        if (!StringUtils.isEmpty(vo.getXzqhdm())) {
            String xzqhdm = vo.getXzqhdm();
            String xzqhJb = tXzqhMapper.getAreaCodeLevel(xzqhdm);
            String subXzqhDigit = XzqhUtils.subXzqhDigit(xzqhJb);
            String xzqhdmLike = vo.getXzqhdm().substring(0, Integer.parseInt(subXzqhDigit));
            vo.setXzqhdm(xzqhdmLike);
        }
        if (Integer.parseInt(WorkOrderFindTypeEnum._1.getKey()) == vo.getType()) {
            vo.setUserId(vo.getUserInfo().getId());
        }
      /*  // 类别  2:待处理
        if (Integer.parseInt(WorkOrderFindTypeEnum._2.getKey()) == vo.getType()) {
            vo.setWorkOrderStatus(Integer.parseInt(WorkOrderStautsEnum._0.getKey()));
        }
        // 类别  3:待支援
        if (Integer.parseInt(WorkOrderFindTypeEnum._3.getKey()) == vo.getType()) {
            vo.setWorkOrderStatus(Integer.parseInt(WorkOrderStautsEnum._1.getKey()));
        }*/
        // 类别  4:处理中
        if (Integer.parseInt(WorkOrderFindTypeEnum._4.getKey()) == vo.getType()) {
            vo.setWorkOrderStatus(Integer.parseInt(WorkOrderStautsEnum._2.getKey()));
            vo.setMaintenanceStatus(Integer.valueOf(MaintainWorkOrderStautsEnum._0.getKey()));
        }
        // 类别  5:待回访
        if (Integer.parseInt(WorkOrderFindTypeEnum._5.getKey()) == vo.getType()) {
            vo.setWorkOrderStatus(Integer.parseInt(WorkOrderStautsEnum._6.getKey()));
        }
        // 类别  7:待我处理的工单
        if (Integer.parseInt(WorkOrderFindTypeEnum._7.getKey()) == vo.getType()) {
            vo.setWorkOrderStatus(Integer.parseInt(WorkOrderStautsEnum._2.getKey()));
            vo.setUserId(vo.getUserInfo().getId());
        }
        if (Integer.parseInt(WorkOrderFindTypeEnum._8.getKey()) == vo.getType()) {
            vo.setUserId(vo.getUserInfo().getId());
        }
        // 待审核工单
        if (Integer.parseInt(WorkOrderFindTypeEnum._9.getKey()) == vo.getType()) {
            vo.setWorkOrderStatus(null);
            vo.setUserId(vo.getUserInfo().getId());
        }
        if (Integer.parseInt(WorkOrderFindTypeEnum._10.getKey()) == vo.getType()) {
            vo.setWorkOrderStatus(Integer.parseInt(WorkOrderStautsEnum._2.getKey()));
            vo.setMaintenanceStatus(Integer.parseInt(MaintainWorkOrderStautsEnum._3.getKey()));
        }
        //已审核（只查询回访以后的审核）
        if (Integer.parseInt(WorkOrderFindTypeEnum._11.getKey()) == vo.getType()) {
            vo.setWorkOrderStatus(Integer.parseInt(WorkOrderStautsEnum._3.getKey()));
            vo.setAudited(1);//0未审核 1已审核
        }
        if (ObjectUtil.isEmpty(vo.getCompanyId())) {
            vo.setCompanyId(vo.getOperateUserCompanyId());
        }
        //查询类型
        vo.setCompanyType(vo.getOperateUserCompanyType());
        // 查询维修工单分页信息
        Page<GetWorkOrderRepairPageDTO> page = new Page<>(vo.getPageid(), vo.getPagesize());
        List<GetWorkOrderRepairPageDTO> records = this.baseMapper.getWorkOrderRepairPage(page, vo);
        if (CollectionUtil.isEmpty(records)) {
            return PageData.ok(page, records);
        }
        // 设置返回值
        for (GetWorkOrderRepairPageDTO item : records) {
            if (ObjectUtil.isNotEmpty(callWorkOrderInfoService.getWorkOrderByPworkOrderId(item.getWorkOrderId()))) {
                WorkOrderInfo pWorkOrderInfo = callWorkOrderInfoService.getWorkOrderByPworkOrderId(item.getWorkOrderId());
                if(ObjectUtil.isNotEmpty(pWorkOrderInfo.getMaintainId())) {
                   item.setMaintainId(pWorkOrderInfo.getMaintainId().toString());
                    item.setMaintainName(systemUserService.getUserInfoByCallCenterUserId(pWorkOrderInfo.getMaintainId().toString()).getNickName());
                }
            }

            item.setWorkOrderStatusName(WorkOrderStautsEnum.getVal(item.getWorkOrderStatus()));
            if (ObjectUtil.equals(item.getWorkOrderServiceStatus(), 3) && ObjectUtil.equals(item.getWorkOrderStatusName(), "处理中")) {
                item.setWorkOrderStatusName("未接单");
            }
            item.setCanCancel(!WorkOrderStautsEnum.getIsComplete(item.getWorkOrderStatus())); // 取反
            if (ObjectUtil.isNotEmpty(item.getWorkOrderType())) {
                item.setWorkTypeName(WorkOrderTypeEnum.getVal(item.getWorkOrderType()));
            }
            item.setEmergencyDegreeName(WorkOrderEmergencyDegreeEnum.getVal(item.getEmergencyDegreeId()));
            if (StringUtils.isNotEmpty(item.getOrderCreateUserId())) {
                item.setCreateUserName(tUserMapper.getAllUserByUuId(item.getOrderCreateUserId()).getNickName());
            }
            if ("1".equals(item.getAudited())) {
                item.setAudited("已审核");
            } else {
                item.setAudited("待审核");
            }
            item.setAreaName(concatAreaName(item.getAreaCode()));
            StringBuilder stringBuilder = new StringBuilder();
            if (StringUtils.isNotEmpty(item.getEvaluation())) {
                List<String> evaluationList = Arrays.asList(item.getEvaluation().substring(1).split(";"));
                if (evaluationList.size() > 1) {
                    for (int i = 0; i < evaluationList.size(); i++) {
                        if (i == evaluationList.size() - 1) {
                            stringBuilder.append(EvaluationEnum.getVal(evaluationList.get(i)));
                        } else {
                            stringBuilder.append(EvaluationEnum.getVal(evaluationList.get(i))).append(",");
                        }
                    }

                } else {
                    stringBuilder.append(EvaluationEnum.getVal(evaluationList.get(0)));
                }
                item.setEvaluationName(stringBuilder.toString());
            }
            Date warrantyExpiryDate = item.getZbrq();
            if (ObjectUtil.isEmpty(warrantyExpiryDate)) {
                item.setIsWarrantyExpiry(null);
            } else
                item.setIsWarrantyExpiry(warrantyExpiryDate.compareTo(new Date()) < (item.getZbq() == null ? 0 : item.getZbq()));
        }
        return PageData.ok(page, records);
    }

    public PageData getWorkOrderRepairDetail(GetWorkOrderRepairDetailVO vo) throws Exception {
        if (!CompanyTypeEnum._00.getKey().equals(vo.getOperateUserCompanyType())) {
            vo.setOrderCreateUserId(vo.getUserInfo().getUuid());
            vo.setOrderBelongCompanyId(vo.getOperateUserCallCenterCompanyId());
        }
        // 查询维修工单主体信息
        WorkOrderInfo workOrder = new WorkOrderInfo();
        workOrder.setId(vo.getWorkOrderId());
        WorkOrderInfo workOrderInfo = workOrderDataMapper.selectOne(new LambdaQueryWrapper<>(workOrder));
        if (ObjectUtil.isNull(workOrderInfo)) {
            return PageData.error("查询维修工单详情失败!");
        }
        WorkOrderRepairDetailDTO workOrderRepairDetailDTO = new WorkOrderRepairDetailDTO();
        WorkOrderRepairInfoDTO workOrderRepairInfoDTO = new WorkOrderRepairInfoDTO();
        BeanUtils.copyProperties(workOrderInfo, workOrderRepairInfoDTO);
        workOrderRepairInfoDTO.setOrderStatus(workOrderInfo.getStatus());
        if (ObjectUtil.isNotEmpty(workOrderInfo.getHandleTypeId())) {
            workOrderRepairInfoDTO.setRepairType(workOrderInfo.getHandleTypeId().toString());
        }
        workOrderRepairInfoDTO.setXzqhdm(workOrderInfo.getXzqhdm());
        workOrderRepairInfoDTO.setGmtCreate(workOrderInfo.getGmtCreate());
        workOrderRepairInfoDTO.setCjsj(new Date(workOrderInfo.getGmtCreate()));
        workOrderRepairInfoDTO.setHandleDesc(workOrderInfo.getHandleDesc());
        workOrderRepairInfoDTO.setOrderStatusDesc(WorkOrderStautsEnum.getVal(workOrderInfo.getStatus()));
        workOrderRepairInfoDTO.setOrderServiceStatus(workOrderInfo.getMaintainStatus());
        workOrderRepairInfoDTO.setOrderServiceStatusDesc(MaintainWorkOrderStautsEnum.getVal(workOrderInfo.getMaintainStatus()));
        if (ObjectUtil.isNotEmpty(workOrderInfo.getUserId())) {
            if (ObjectUtil.isNotEmpty(systemUserService.getUserInfoByCallCenterUserId(workOrderInfo.getUserId().toString()))) {
                workOrderRepairInfoDTO.setCreateUserName(systemUserService.getUserInfoByCallCenterUserId(workOrderInfo.getUserId().toString()).getNickName());
            }
        }
        Company pCompany = businessCompanyService.getCompanyByCallCenterCompanyId(workOrderInfo.getCompanyId());
        if (ObjectUtil.isEmpty(callWorkOrderInfoService.getWorkOrderByPworkOrderId(workOrderInfo.getId()))) {
            workOrderRepairInfoDTO.setMaintainId(ccUserService.getCcUser(workOrderInfo.getMaintainId()).getAgentUserId());
            workOrderRepairInfoDTO.setSubsidiaryCompanyId(pCompany.getCompanyid());
            workOrderRepairInfoDTO.setSubsidiaryCompanyName(pCompany.getCompanyname());
        } else {
            WorkOrderInfo pWorkOrderInfo = callWorkOrderInfoService.getWorkOrderByPworkOrderId(workOrderInfo.getId());
            if (ObjectUtil.isNotEmpty(pWorkOrderInfo)) {
                Company subsidiaryCompany = businessCompanyService.getCompanyByCallCenterCompanyId(pWorkOrderInfo.getCompanyId());
                workOrderRepairInfoDTO.setSubsidiaryCompanyId(subsidiaryCompany.getCompanyid());
                workOrderRepairInfoDTO.setSubsidiaryCompanyName(subsidiaryCompany.getCompanyname());
                workOrderRepairInfoDTO.setMaintainId(ccUserService.getCcUser(pWorkOrderInfo.getMaintainId()).getAgentUserId());
            }
        }
        workOrderRepairInfoDTO.setCompanyId(pCompany.getCompanyid());
        workOrderRepairInfoDTO.setCompanyName(pCompany.getCompanyname());
        //是否可以审核
        if (workOrderInfo.getAudited() == 0 && (workOrderInfo.getStatus() == 3 || workOrderInfo.getStatus() == 6)) {
            workOrderRepairInfoDTO.setAllowAudit(1);
        } else {
            workOrderRepairInfoDTO.setAllowAudit(0);
        }
        if (ObjectUtil.isNotEmpty(workOrderInfo.getFaultType())) {
            workOrderRepairInfoDTO.setFaultTypeDesc(FaultTypeEnum.getVal(workOrderInfo.getFaultType()));
        }
        StringBuilder stringBuilder = new StringBuilder();
        if (StringUtils.isNotEmpty(workOrderInfo.getEvaluation())) {
            List<String> evaluationList = Arrays.asList(workOrderInfo.getEvaluation().substring(1).split(";"));
            if (evaluationList.size() > 1) {
                for (int i = 0; i < evaluationList.size(); i++) {
                    if (i == evaluationList.size() - 1) {
                        stringBuilder.append(EvaluationEnum.getVal(evaluationList.get(i)));
                    } else {
                        stringBuilder.append(EvaluationEnum.getVal(evaluationList.get(i))).append(",");
                    }
                }

            } else {
                stringBuilder.append(EvaluationEnum.getVal(evaluationList.get(0)));
            }
            workOrderRepairInfoDTO.setEvaluationName(stringBuilder.toString());
        }
        if (workOrderInfo.getHandleTypeId() != null) {
            workOrderRepairInfoDTO.setRepairTypeDesc(HandleTypeEnum.getVal(workOrderInfo.getHandleTypeId()));
        }
        workOrderRepairInfoDTO.setConsultTypeName(ConsultTypeEnum.getVal(workOrderInfo.getConsultType()));
        if (ObjectUtil.isNotEmpty(workOrderInfo.getMaintainId())) {
            // 2024-12-03 修复查询企业工单详情接口报错 - 从长效管护数据库查询施工人员姓名
            CcUser ccUser = ccUserService.getCcUser(workOrderInfo.getMaintainId());
            workOrderRepairInfoDTO.setHandleUserName(ObjectUtil.isNull(ccUser) ? StrUtil.EMPTY : ccUser.getName());
        }
        workOrderRepairInfoDTO.setEmergencyDegreeName(WorkOrderEmergencyDegreeEnum.getVal(workOrderInfo.getEmergencyDegreeId()));
        workOrderRepairInfoDTO.setTaskTypeName(WorkOrderTypeEnum.getVal(workOrderInfo.getType().toString()));
        workOrderRepairInfoDTO.setCallCenterCompanyId(Long.parseLong(vo.getUserInfo().getCallCenterCompanyId()));
        //查询图片
        workOrderRepairDetailDTO.setPicList(workOrderRepairPicService.getPicList(vo.getWorkOrderId()));
        Company company = businessCompanyService.getCompanyByCallCenterCompanyId(Long.parseLong(vo.getUserInfo().getCallCenterCompanyId()));
        workOrderRepairInfoDTO.setOrderCreateSource(ObjectUtil.isNotNull(company) ? company.getCompanyname() : StrUtil.EMPTY);
        workOrderRepairInfoDTO.setProcureSourceName(tParamService.getNameByParamTypeAndValue(DictTypeEnum.PROCURE_SOURCE.getParamType(), String.valueOf(workOrderInfo.getProcureSource())));


        if (StringUtils.isNotEmpty(workOrderInfo.getAppealCategory())) {
            if ("01".equals(workOrderInfo.getAppealCategory())) {
                workOrderRepairInfoDTO.setAppealCategoryName("故障类");
            } else {
                workOrderRepairInfoDTO.setAppealCategoryName("售后服务类");
            }
        }
        if (ObjectUtil.isNotEmpty(workOrderInfo.getWorkTypeId())) {
            if (workOrderInfo.getWorkTypeId() == 32) {
                workOrderRepairInfoDTO.setWorkTypeName("上门维修");
            } else {
                workOrderRepairInfoDTO.setWorkTypeName("调试");
            }
        }
        workOrderRepairInfoDTO.setCanCancel(!WorkOrderStautsEnum.getIsComplete(workOrderInfo.getStatus())); // 取反
        CustomerDTO customerDetail = crmCustomerService.getCustomerById(workOrderInfo.getCustomerId());
        CustomerStaffDTO customerStaffDTO = customerStaffService.getMainCustomerStaff(workOrderInfo.getCustomerId());
        // 查询客户房屋信息
        CustomerHouseDTO houseInfo = customerHouseService.getHouseDetail(workOrderInfo.getCustomerHouseId());
        // 查询设备信息
        workOrderRepairDetailDTO.setEquipmentInfoList(equipmentService.getEquipmentInfoListByDDid(houseInfo.getHouseUuid()));
        QueryWrapper<IsInstallInfo> wrapper = new QueryWrapper<>();
        wrapper.eq("dd_id", houseInfo.getHouseUuid());
        wrapper.eq("sfsc", 0);
        IsInstallInfo isInstallInfo = isInstallInfoService.getOne(wrapper);
        if (ObjectUtil.isNotEmpty(isInstallInfo)) {
            if (isInstallInfo.getZbrq() == null || isInstallInfo.getZbq() == 0) {
                workOrderRepairInfoDTO.setSfzb("未选择是否质保");
            } else if (isInstallInfo.getZbrq().compareTo(new Date()) < isInstallInfo.getZbq()) {
                workOrderRepairInfoDTO.setSfzb("质保内");
            } else {
                workOrderRepairInfoDTO.setSfzb("质保外");
            }
            // 处理安装日期
            String installDateStr = StrUtil.EMPTY;
            if (ObjectUtil.isNotNull(isInstallInfo)) {
                installDateStr = new SimpleDateFormat("yyyy-MM-dd").format(isInstallInfo.getAzwcrq());
            }
            workOrderRepairInfoDTO.setInstallDateStr(installDateStr);
        }
        //零件信息
        // 2024-12-04 项目组决定只有工单完成后，才展示配件相关信息
        if (ObjectUtil.isNotNull(workOrderInfo.getMaintainStatus())
                && MaintainWorkOrderStautsEnum._2.getKey().equals(String.valueOf(workOrderInfo.getMaintainStatus()))) {
            List<SparePartDto> partList = sparePartMapper.queryPart(vo.getWorkOrderId().toString());
            if (ObjectUtil.isNotEmpty(isInstallInfo)) {
              if (isInstallInfo.getZbrq().compareTo(new Date()) < isInstallInfo.getZbq()) {
                    partList.forEach(item->item.setTotalPrice(new BigDecimal(0)));
                }
            }
            List<SparePartDto> repairPriceList = new ArrayList<>();
            SparePartDto wxfy = new SparePartDto();
            wxfy.setAmount("1");
            wxfy.setPartName("维修费用");
            wxfy.setTotalPrice(ObjectUtil.isNull(workOrderInfo.getRepairPrice()) ? BigDecimal.ZERO : workOrderInfo.getRepairPrice());
            repairPriceList.add(wxfy);
            workOrderRepairInfoDTO.setRepairPriceList(repairPriceList);
            workOrderRepairInfoDTO.setPartList(partList);
        }
        // 组装客户信息
        customerDetail.setAddress(houseInfo.getAddress());
        customerDetail.setHouseNumber(houseInfo.getHouseNumber());
        customerDetail.setEnergyMeterNumber(houseInfo.getElectricityMeterNumbers());
        workOrderInfo.setHouseNumber(houseInfo.getHouseNumber());
        workOrderRepairDetailDTO.setWorkOrderInfo(workOrderRepairInfoDTO);
        // 组装返回值参数
        workOrderRepairDetailDTO.setCustomerDetail(customerDetail);
        workOrderRepairDetailDTO.setCustomerStaffDTOrDetail(customerStaffDTO);
        workOrderRepairDetailDTO.setHouseList(Collections.singletonList(houseInfo));
        return PageData.ok("workOrderRepairDetail", workOrderRepairDetailDTO);
    }

    /**
     * 完成维修工单
     */
    @Override
    @CallCenterTransactional
    public PageData completeOrderRepair(CompleteOrderRepairVo vo) throws Exception {
        //获取当前工单id
        Long workOrderId = vo.getWorkOrderId();
        //封装工单表数据
        WorkOrderInfo workOrderInfo = callWorkOrderInfoService.selectByPrimaryKey(workOrderId);
        if (ObjectUtil.isNull(workOrderInfo)) {
            throw new IllegalBusinessException("未查询到工单信息！");
        }

        //修改工单表中的状态如果不是等待配件
        if (vo.getRepairResult() == 0) {
            workOrderInfo.setMaintainStatus(Integer.valueOf(MaintainWorkOrderStautsEnum._2.getKey()));
            workOrderInfo.setStatus(Integer.valueOf(WorkOrderStautsEnum._6.getKey()));
        } else {
            workOrderInfo.setMaintainStatus(Integer.valueOf(MaintainWorkOrderStautsEnum._4.getKey()));
            workOrderInfo.setStatus(Integer.valueOf(WorkOrderStautsEnum._2.getKey()));
        }
        workOrderInfo.setGmtModified(vo.getOperateTimeStamp());
        workOrderInfo.setLatitude(vo.getLatitude());
        workOrderInfo.setLongitude(vo.getLongitude());
        workOrderInfo.setHandleTypeId(Integer.parseInt(vo.getRepairType()));
        workOrderInfo.setRepairPrice(vo.getRepairPrice());
        workOrderInfo.setCharged(vo.getCharged());
        workOrderInfo.setBaseDistance(vo.getBaseDistance());
        workOrderInfo.setRoundTrip(vo.getRoundTrip());
        workOrderInfo.setRepairResult(vo.getRepairResult());
        workOrderInfo.setHandleDesc(vo.getHandleDesc());
        //如果冷媒类型为空那么就是空
        if (StringUtils.isNotEmpty(vo.getRefrigerantType())) {
            workOrderInfo.setRefrigerantType(vo.getRefrigerantType());
            workOrderInfo.setRefrigerantPrice(vo.getRefrigerantPrice());
            workOrderInfo.setRefrigerantAmount(vo.getRefrigerantAmount());
        }
        workOrderInfo.setPersonliable(vo.getPersonliable());
        workOrderInfo.setPaymentState(vo.getPaymentState());
        //如果配件id为空那么就是空
        if (StringUtils.isNotEmpty(vo.getPartId())) {
            this.savePartsId(workOrderId.toString(), vo.getStatus(), vo.getPartId(), vo.getAmount(), vo.getOperateUserCompanyId());
        }
        int result = callWorkOrderInfoService.updateByPrimaryKey(workOrderInfo);
        //如果有上级工单id 递归更新并保存上级工单日志
        if (ObjectUtil.isNotEmpty(workOrderInfo.getPWorkOrderId())) {
            updateWorkOrderInfo(workOrderInfo.getPWorkOrderId(), vo);
        }


        CcUser ccUser = ccUserService.getCcUser(workOrderInfo.getMaintainId());
        updateUserCoordinate(ccUser.getId(), vo.getLongitude(), vo.getLatitude(), vo.getOperateUserPhone());
        //判断是否修改成功工单表状态
        if (result > 0) {
            //写工单记录，返回工单记录id
            WorkOrderRecord workOrderRecord = new WorkOrderRecord();
            workOrderRecord.setWorkOrderId(workOrderId);
            //如果不是等待配件
            if (vo.getRepairResult() == 0) {
                workOrderRecord.setDesc("维修完成");
                workOrderRecord.setStatus(Integer.parseInt(WorkOrderStautsEnum._6.getKey()));
            } else {
                workOrderRecord.setDesc("等待配件");
                workOrderRecord.setStatus(Integer.parseInt(WorkOrderStautsEnum._2.getKey()));
            }
            workOrderRecord.setMaintainId(ccUser.getId());
            workOrderRecord.setIsDelete(Integer.valueOf(DeleteEnum._0.getKey()));
            workOrderRecord.setGmtCreate(vo.getOperateTimeStamp());
            workOrderRecord.setGmtModified(vo.getOperateTimeStamp());
            workOrderRecord.setLongitude(vo.getLongitude());
            workOrderRecord.setLatitude(vo.getLatitude());
            workOrderRecord.setDesc("故障描述:" + paramParamMapper.getFaultDescById(vo.getFaultType()));
            workOrderRecord.setLongitude(vo.getLongitude());
            workOrderRecord.setLatitude(vo.getLatitude());
            workOrderRecordService.saveWorkOrderRecord(workOrderRecord);
        }
        //保存维修工单图片信息
        UpdatePicInfoVO updatePicInfoVO = new UpdatePicInfoVO();
        BeanUtils.copyProperties(vo, updatePicInfoVO);
        updatePicInfoVO.setWorkOrderId(workOrderId);
        updatePicInfoVO.setSavePicList(vo.getSavePicList());
        updatePicInfoVO.setUserInfo(vo.getUserInfo());
        updatePicInfoVO.setOperateDate(vo.getOperateDate());
        callWorkOrderPicService.insertPicInfo(updatePicInfoVO);
        return PageData.ok("成功");
    }

    //添加配件
    public int savePartsId(String workOrderId, String status, String partId, String partAmount, String manufactureId) throws Exception {
        int cnt = 0;
        if (null == status && "".equals(status)) {
            return cnt;
        }
        HashMap<String, Object> vo = new HashMap<>();
        vo.put("manufactureId", manufactureId);
        vo.put("workOrderId", workOrderId);
        vo.put("partId", partId);
        vo.put("partsNum", partAmount);
        vo.put("status", status);

        //先删除本工单已经保存的部件
        sparePartMapper.delParts(vo);
        List<SaveOrderPartUsageVo> list = new ArrayList<>();
        //插入新添加的部件
        if (partId.indexOf(",") < 0) {
            SaveOrderPartUsageVo sopuVo = new SaveOrderPartUsageVo();
            sopuVo.setAmount(partAmount);
            sopuVo.setPartId(partId);
            sopuVo.setStatus(status);
            sopuVo.setPrice(getSparePart(manufactureId, partId).getPrice().toString());
            list.add(sopuVo);
        } else {
            String[] partIds = partId.split(",");
            String[] partAmounts = partAmount.split(",");
            for (int i = 0; i < partIds.length; i++) {
                SaveOrderPartUsageVo sopuVo = new SaveOrderPartUsageVo();
                sopuVo.setAmount(partAmounts[i]);
                sopuVo.setPartId(partIds[i]);
                sopuVo.setStatus(status);
                sopuVo.setPrice(getSparePart(manufactureId, partIds[i]).getPrice().toString());
                list.add(sopuVo);
            }
        }

        vo.put("list", list);
        //都存入了配件表，所以只需保证status正确就可以
        cnt = sparePartMapper.savePartsId(vo);
        if (cnt <= 0) {
            throw new Exception("修改配件失败!");
        }
        return cnt;
    }

    public SparePart getSparePart(String manufactureId, String partId) {
        SparePartVo spareParVo = new SparePartVo();
        spareParVo.setPartId(partId);
        spareParVo.setManufactureId(manufactureId);
        spareParVo.setPartTypeId("all");
        List<SparePart> spareParts = sparePartMapper.getPartsByTypeId(spareParVo);
        return spareParts.get(0) == null ? new SparePart() : spareParts.get(0);
    }

    public PageData getSparePart(String companyId) throws Exception {
        /*Company company = businessCompanyService.getCompany(companyId);*/
        SparePartVo spareParVo = new SparePartVo();
        spareParVo.setManufactureId(companyId);
        spareParVo.setPartTypeId("all");
        return PageData.ok("SparePart", sparePartMapper.getPartsByTypeId(spareParVo));
    }

    @Override
    public PageData getParamsByTypeValue(ParamsVo vo) {
        return PageData.ok("paramList", paramParamMapper.getParamsByTypeValue(vo.getTypeValue()));
    }

    @Override
    public CommonResult<?> evaluationWorkOrder(EvaluationWorkOrderVo vo) {
        vo.setUserId(Long.parseLong(vo.getOperateUserCallCenterCompanyId()));
        List<String> evaluationList = vo.getEvaluation();
        String evaluation = "";
        if (evaluationList != null && evaluationList.size() > 0) {
            evaluation = ";";
            for (String s : evaluationList) {
                evaluation += s + ";";
            }
        }
        vo.setEvaluationString(evaluation);

        WorkOrderInfo workOrderInfo = new WorkOrderInfo();
        workOrderInfo.setId(vo.getWorkOrderId());
        workOrderInfo.setEvaluation(vo.getEvaluationString());
        int count = callWorkOrderInfoService.updateByPrimaryKey(workOrderInfo);
        if (count > 0) {
            return CommonResult.ok("操作成功");
        } else {
            return CommonResult.error("操作失败");
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public CommonResult<?> updateWorkOrderStatus(WorkOrderStatusVo vo, String xzqhdms) throws Exception {
        WorkOrderInfo workOrderInfo = callWorkOrderInfoService.selectByPrimaryKey(vo.getWorkOrderId());
        if (null == workOrderInfo) {
            CommonResult.error("未查到此工单");
        }
        Company pCompany = businessCompanyService.getCompany(vo.getSubsidiaryCompanyId());
        if(ObjectUtil.isEmpty(pCompany) && ObjectUtil.isEmpty(pCompany.getCcCompanyId())){
            CommonResult.error("派单企业未创建客服中心");
        }
        //如果新建工单时派单就是选的当前公司，就不能再复制工单了
        if (StringUtils.isNotEmpty(vo.getSubsidiaryCompanyId()) && !vo.getSubsidiaryCompanyId().equals(vo.getOperateUserCompanyId())) {// 修改状态
            if (ObjectUtil.isEmpty(callWorkOrderInfoService.getWorkOrderByPworkOrderId(workOrderInfo.getId()))) {
                workOrderInfo.setStatus(Integer.parseInt(WorkOrderStautsEnum._2.getKey()));
                // 处理人id
                workOrderInfo.setMaintainId(100000000L);
                workOrderInfo.setMaintainStatus(Integer.parseInt(MaintainWorkOrderStautsEnum._3.getKey()));
                workOrderInfo.setGmtModified(System.currentTimeMillis());
                // 更新工单信息
                int result = callWorkOrderInfoService.updateByPrimaryKey(workOrderInfo);
                if (result <= 0) {
                    //事务回滚
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                    return CommonResult.error("保存维修人失败");
                }
                WorkOrderRecord record = new WorkOrderRecord();
                record.setGmtCreate(System.currentTimeMillis());
                record.setGmtModified(System.currentTimeMillis());
                record.setDelete(DeleteEnum._0.getKey());
                record.setStatus(Integer.parseInt(WorkOrderStautsEnum._2.getKey()));
                record.setDesc(vo.getOperateUserName()+"向"+pCompany.getCompanyname()+"转派了工单");
                record.setWorkOrderId(workOrderInfo.getId());
                record.setUserId(vo.getUserInfo().getCallCenterUserId());
                workOrderRecordService.saveWorkOrderRecord(record);
                // 修改状态
                workOrderInfo.setStatus(Integer.parseInt(WorkOrderStautsEnum._2.getKey()));
                // 处理人id
                TUser installUserInfo = systemUserService.getUserInfoByUserId(vo.getHandelUserId());
                workOrderInfo.setMaintainStatus(Integer.parseInt(MaintainWorkOrderStautsEnum._3.getKey()));
                workOrderInfo.setCompanyId(Long.parseLong(pCompany.getCcCompanyId()));
                workOrderInfo.setMaintainId(installUserInfo.getCallCenterUserId());
                workOrderInfo.setPWorkOrderId(workOrderInfo.getId());
                workOrderInfo.setUserId(workOrderInfo.getUserId());
                workOrderDataMapper.insert(workOrderInfo);
                WorkOrderRecord record1 = new WorkOrderRecord();
                record1.setGmtCreate(vo.getOperateTimeStamp());
                record1.setGmtModified(vo.getOperateTimeStamp());
                record1.setIsDelete(DeleteEnum._0.getKey());
                record1.setStatus(Integer.parseInt(WorkOrderStautsEnum._2.getKey()));
                record1.setDesc(vo.getOperateUserName()+"向"+pCompany.getCompanyname()+"转派了工单");
                record1.setWorkOrderId(workOrderInfo.getId());
                record1.setUserId(vo.getUserInfo().getCallCenterUserId());//转换为长效管护的id
                workOrderRecordService.saveWorkOrderRecord(record1);
            } else {
                TUser installUserInfo = systemUserService.getUserInfoByUserId(vo.getHandelUserId());
                workOrderInfo.setStatus(Integer.parseInt(WorkOrderStautsEnum._2.getKey()));
                // 处理人id
                workOrderInfo.setMaintainId(100000000L);
                workOrderInfo.setMaintainStatus(Integer.parseInt(MaintainWorkOrderStautsEnum._3.getKey()));
                workOrderInfo.setGmtModified(System.currentTimeMillis());
                // 更新工单信息
                int result = callWorkOrderInfoService.updateByPrimaryKey(workOrderInfo);
                if (result <= 0) {
                    //事务回滚
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                    return CommonResult.error("保存维修人失败");
                }
                WorkOrderRecord record = new WorkOrderRecord();
                record.setGmtCreate(System.currentTimeMillis());
                record.setGmtModified(System.currentTimeMillis());
                record.setDelete(DeleteEnum._0.getKey());
                record.setStatus(Integer.parseInt(WorkOrderStautsEnum._2.getKey()));
                record.setDesc(WorkOrderRecordDescEnum._10.getVal());
                record.setWorkOrderId(workOrderInfo.getId());
                record.setUserId(vo.getUserInfo().getCallCenterUserId());
                workOrderRecordService.saveWorkOrderRecord(record);
                // 修改状态
                workOrderInfo.setStatus(Integer.parseInt(WorkOrderStautsEnum._2.getKey()));
                // 处理人id
                workOrderInfo.setMaintainStatus(Integer.parseInt(MaintainWorkOrderStautsEnum._3.getKey()));
                workOrderInfo.setCompanyId(Long.parseLong(pCompany.getCcCompanyId()));
                workOrderInfo.setMaintainId(installUserInfo.getCallCenterUserId());
                workOrderInfo.setPWorkOrderId(workOrderInfo.getId());
                workOrderInfo.setUserId(workOrderInfo.getUserId());
                workOrderInfo.setId(callWorkOrderInfoService.getWorkOrderByPworkOrderId(workOrderInfo.getId()).getId());
                int result1 = callWorkOrderInfoService.updateByPrimaryKey(workOrderInfo);
                if (result1 <= 0) {
                    //事务回滚
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                    return CommonResult.error("保存维修人失败");
                }
                WorkOrderRecord record1 = new WorkOrderRecord();
                record1.setGmtCreate(vo.getOperateTimeStamp());
                record1.setGmtModified(vo.getOperateTimeStamp());
                record1.setIsDelete(DeleteEnum._0.getKey());
                record1.setStatus(Integer.parseInt(WorkOrderRecordDescEnum._1.getKey()));
                record1.setDesc(vo.getOperateUserName()+"向"+installUserInfo.getNickName()+"指派了工单");
                record1.setWorkOrderId(workOrderInfo.getId());
                record1.setUserId(vo.getUserInfo().getCallCenterUserId());//转换为长效管护的id
                workOrderRecordService.saveWorkOrderRecord(record1);
            }
        } else {
            TUser installUserInfo = systemUserService.getUserInfoByUserId(vo.getHandelUserId());
            if (ObjectUtil.isEmpty(installUserInfo.getCallCenterUserId())) {
                return CommonResult.error("此用户的公司未创建客服中心");
            }
            if (workOrderInfo != null && workOrderInfo.getPWorkOrderId() != null) {
                updateworkOrderRecord(workOrderInfo.getPWorkOrderId(), workOrderInfo, vo);
            }            // 修改状态
            workOrderInfo.setStatus(Integer.parseInt(WorkOrderStautsEnum._2.getKey()));
            // 处理人id
            workOrderInfo.setMaintainId(installUserInfo.getCallCenterUserId());
            workOrderInfo.setMaintainStatus(Integer.parseInt(MaintainWorkOrderStautsEnum._3.getKey()));
            workOrderInfo.setGmtModified(System.currentTimeMillis());
            // 更新工单信息
            int result = callWorkOrderInfoService.updateByPrimaryKey(workOrderInfo);
            if (result <= 0) {
                //事务回滚
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return CommonResult.error("保存维修人失败");
            }
            // 插入工单记录信息
            WorkOrderRecord record = new WorkOrderRecord();
            record.setGmtCreate(System.currentTimeMillis());
            record.setGmtModified(System.currentTimeMillis());
            record.setDelete(DeleteEnum._0.getKey());
            record.setStatus(Integer.parseInt(WorkOrderStautsEnum._2.getKey()));
            record.setDesc(vo.getOperateUserName()+"向"+installUserInfo.getNickName()+"指派了工单");
            record.setWorkOrderId(workOrderInfo.getId());
            record.setUserId(vo.getUserInfo().getCallCenterUserId());
            workOrderRecordService.saveWorkOrderRecord(record);
        }
        return CommonResult.ok("指派成功");
    }

    /**
     * 取消工单
     *
     * @param
     * @return
     */
    @Override
    public CommonResult<?> closeWorkOrder(CloseWorkOrderVo vo) {
        int resCode = 1;
        Long userId = vo.getUserInfo().getCallCenterUserId();
        Long workOrderId = vo.getWorkOrderId();
        try {
            WorkOrderInfo workOrderInfo = callWorkOrderInfoService.selectByPrimaryKey(workOrderId);
            if (1 == vo.getType()) {
                Integer status = workOrderInfo.getStatus();
                if ('3' == status || '6' == status) {
                    return CommonResult.error("已完成的工单不可取消");
                } else {
                    workOrderInfo.setIsDelete(1);
                    workOrderInfo.setGmtModified(System.currentTimeMillis());
                    callWorkOrderInfoService.updateByPrimaryKey(workOrderInfo);
                    WorkOrderRecord workOrderRecord = new WorkOrderRecord();
                    workOrderRecord.setDelete(1);
                    workOrderRecord.setGmtModified(System.currentTimeMillis());
                    workOrderRecord.setWorkOrderId(workOrderId);
                    workOrderRecordMapper.deleteOrderRecordByOrderInfoId(workOrderRecord);
                }
            } else if (0 == vo.getType()) {
                workOrderInfo.setStatus(Integer.parseInt(WorkOrderStautsEnum._4.getKey()));
                workOrderInfo.setDesc("该工单已被取消");
                workOrderInfo.setIsDelete(0);
                workOrderInfo.setGmtModified(System.currentTimeMillis());
                callWorkOrderInfoService.updateByPrimaryKey(workOrderInfo);
                WorkOrderRecord workOrderRecord = new WorkOrderRecord();
                workOrderRecord.setDesc("该工单已被取消");
                workOrderRecord.setWorkOrderId(workOrderId);
                workOrderRecord.setStatus(Integer.parseInt(WorkOrderStautsEnum._4.getKey()));
                workOrderRecord.setGmtCreate(System.currentTimeMillis());
                workOrderRecord.setGmtModified(System.currentTimeMillis());
                workOrderRecord.setUserId(userId);
                workOrderRecord.setDelete(0);
                workOrderRecordMapper.insert(workOrderRecord);
            } else {
                return CommonResult.error("没有此工单类型");
            }
            return CommonResult.ok();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return CommonResult.error("取消工单失败");
    }

    @Override
    public int auditWorkOrder(AuditWorkOrderVo vo) {
        int code = 1;
        try {
            if ("".equals(vo.getTimeoutType())) vo.setTimeoutType("0");
            WorkOrderTimeoutTypeEnum timeoutTypeEnum = WorkOrderTimeoutTypeEnum.valueOf("_" + vo.getTimeoutType());
            vo.setFines(timeoutTypeEnum.getFines());
            int res = workOrderDataMapper.auditWorkOrder(vo);
            workOrderDataMapper.insertAuditedRecord(vo);
            //审核不通过重新派单
            if (0 == vo.getQualified()) {
                WorkOrderRecord workOrderRecord = new WorkOrderRecord();
                workOrderRecord.setWorkOrderId(vo.getWorkOrderId());
                workOrderRecord.setDesc("审核不通过");
                workOrderRecord.setUserId(vo.getUserId());

                //获取当前工单id
                Long workOrderId = workOrderRecord.getWorkOrderId();
                //获取当前时间戳
                Long gmtModified = System.currentTimeMillis();
                //封装工单表数据
                WorkOrderInfo workOrderInfo = new WorkOrderInfo();
                workOrderInfo.setId(workOrderId);
                workOrderInfo.setStatus(Integer.parseInt(WorkOrderStautsEnum._0.getKey()));
                workOrderInfo.setGmtModified(gmtModified);
                //修改工单表中的状态
                int result = workOrderDataMapper.updateWorkOrderInfoStatus(workOrderInfo);
                //重置审核状态
                workOrderDataMapper.resetAuditState(workOrderId);
                //删除录入的审核信息
                workOrderDataMapper.removeAuditedRecord(workOrderId);
                workOrderInfo = callWorkOrderInfoService.selectByPrimaryKey(workOrderId);

                //判断是否修改成功工单表状态
                if (result > 0) {
                    //写工单记录，返回工单记录id
                    workOrderRecord.setStatus(Integer.parseInt(WorkOrderStautsEnum._0.getKey()));
                    workOrderRecord.setDelete(DeleteEnum._0.getKey());
                    workOrderRecord.setGmtCreate(gmtModified);
                    workOrderRecord.setGmtModified(gmtModified);
                    workOrderRecordMapper.insert(workOrderRecord);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            code = 0;
        }
        return code;
    }

    /**
     * 工单回访
     *
     * @param vo
     * @return
     */
    @Override
    public Long workOrderVisit(WorkOrderVisitVo vo) {
        Long code = null;
        long timeMillis = System.currentTimeMillis();
        try {
            //修改工单状态
            WorkOrderInfo workOrderInfo = callWorkOrderInfoService.selectByPrimaryKey(vo.getWorkOrderId());
            workOrderInfo.setStatus(Integer.parseInt(WorkOrderStautsEnum._3.getKey()));
            workOrderInfo.setGmtModified(timeMillis);
            if (ObjectUtil.isNotNull(vo.getSatisfaction())) {
                workOrderInfo.setSatisfaction(vo.getSatisfaction());
            }
            callWorkOrderInfoService.updateByPrimaryKey(workOrderInfo);
            //新增工单记录
            WorkOrderRecord record = new WorkOrderRecord();
            record.setGmtCreate(timeMillis);
            record.setGmtModified(timeMillis);
            record.setDelete(DeleteEnum._0.getKey());
            record.setStatus(Integer.parseInt(WorkOrderStautsEnum._3.getKey()));
            if (ObjectUtil.isNotNull(vo.getSatisfaction())) {
                record.setDesc(vo.getDesc());
            } else {
                record.setDesc("回访描述:" + vo.getDesc());
            }
            record.setWorkOrderId(vo.getWorkOrderId());
            record.setUserId(vo.getUserId());
            if (StringUtils.isNotEmpty(vo.getVisitEval())) {
                record.setVisiteval(vo.getVisitEval());
            }
            workOrderRecordMapper.insert(record);
            code = callWorkOrderInfoService.selectByPrimaryKey(workOrderInfo.getId()).getClienteleId();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return code;
    }

    @Override
    public List<ParamTypeDto> getDictionaryTreeValue() {
        List<ParamTypeDto> res = new ArrayList();
        List<ParamTypeDto> list = paramParamMapper.getDictionaryTreeValue();
        for (ParamTypeDto paramTypeDto : list) {
            List<ParamParamDto> resParamList = new ArrayList();
            ParamTypeDto resParamTypeDto = new ParamTypeDto();

            List<ParamParamDto> paramParamList = paramTypeDto.getParamParamList();
            for (ParamParamDto paramParamDto : paramParamList) {
                //默认指定 长度为2时为最高级 (后续可添加数据库字段指定最高级)
                if (paramParamDto.getParamValue().length() == 2) {
                    ParamParamDto paramParamDtoTree = buildTree(paramParamDto, paramParamList);
                    resParamList.add(paramParamDtoTree);
                }
            }
            resParamTypeDto.setParamParamList(resParamList);
            resParamTypeDto.setTypeValue(paramTypeDto.getTypeValue());
            res.add(resParamTypeDto);
        }
        return res;
    }

    public ParamParamDto buildTree(ParamParamDto paramParamDto, List<ParamParamDto> paramParamList) {
        List<ParamParamDto> childrens = new ArrayList();
        for (ParamParamDto paramDto : paramParamList) {
            if (!(paramDto.getParamValue().equals(paramParamDto.getParamValue()))
                    && paramDto.getParamValue().length() > paramParamDto.getParamValue().length()
                    && paramParamDto.getParamValue().equals(paramDto.getParamValue().substring(0, paramParamDto.getParamValue().length()))) {
                childrens.add(buildTree(paramDto, paramParamList));
            }
        }
        paramParamDto.setChildren(childrens);
        return paramParamDto;
    }

    private String concatAreaName(String xzqhdm) throws Exception {
        XzqhDTO tXzqh = xzqhService.getAreaInfo(xzqhdm);
        if (ObjectUtil.isNotNull(tXzqh)) {
            return tXzqh.getXzqhmc();
        }
        return null;
    }

    @Override
    public List<WorkOrderListExportDto> exportWorkOrderInfo(WorkOrderListVo vo) {
        if (null == vo) {
            vo = new WorkOrderListVo();
        }
        if (vo.getEvaluation().isEmpty()) {
            vo.setEvaluation(null);
        }
        vo.setCompanyId(Long.parseLong(vo.getOperateUserCompanyId()));
        vo.setEquipmentExtendCompanyId(vo.getOperateUserCompanyId());
        /*String[] strings = XzqhUtils.getXzqhdms(vo.getUserInfo().getAreacode());
        vo.setXzqhdms(strings);*/
        if (ObjectUtil.isNotNull(vo.getWorkOrderStatus())) {
            switch (vo.getWorkOrderStatus()) {
                case 2:
                    vo.setMaintenanceStatus(0);
                    break;
                case 10:
                    vo.setWorkOrderStatus(2);
                    vo.setMaintenanceStatus(3);
                    break;
                default:
                    break;
            }
        }
        // 类别  1:我创建
        // 向vo中添加userId查询我添加的工单
        /*if (Integer.parseInt(WorkOrderFindTypeEnum._1.getKey()) == vo.getType()) {
            vo.setUserId(Long.parseLong(vo.getUserInfo().getId()));
        }
        // 类别  2:待处理
        if (Integer.parseInt(WorkOrderFindTypeEnum._2.getKey()) == vo.getType()) {
            vo.setWorkOrderStatus(Integer.parseInt(WorkOrderStautsEnum._0.getKey()));
        }*/
        // 类别  3:待支援
        if (Integer.parseInt(WorkOrderFindTypeEnum._3.getKey()) == vo.getType()) {
            vo.setWorkOrderStatus(Integer.parseInt(WorkOrderStautsEnum._1.getKey()));
        }
        // 类别  4:处理中
        if (Integer.parseInt(WorkOrderFindTypeEnum._4.getKey()) == vo.getType()) {
            vo.setWorkOrderStatus(Integer.parseInt(WorkOrderStautsEnum._2.getKey()));
            vo.setMaintenanceStatus(Integer.valueOf(MaintainWorkOrderStautsEnum._0.getKey()));
        }
        // 类别  5:待回访
        if (Integer.parseInt(WorkOrderFindTypeEnum._5.getKey()) == vo.getType()) {
            vo.setWorkOrderStatus(Integer.parseInt(WorkOrderStautsEnum._6.getKey()));
        }
        // 类别  7:待我处理的工单
        if (Integer.parseInt(WorkOrderFindTypeEnum._7.getKey()) == vo.getType()) {
            vo.setWorkOrderStatus(Integer.parseInt(WorkOrderStautsEnum._2.getKey()));
            vo.setUserId(Long.parseLong(vo.getUserInfo().getId()));
        }
        if (Integer.parseInt(WorkOrderFindTypeEnum._8.getKey()) == vo.getType()) {
            vo.setUserId(Long.parseLong(vo.getUserInfo().getId()));
        }
        // 待审核工单
        if (Integer.parseInt(WorkOrderFindTypeEnum._9.getKey()) == vo.getType()) {
            vo.setWorkOrderStatus(null);
            vo.setUserId(Long.parseLong(vo.getUserInfo().getId()));
        }
        if (Integer.parseInt(WorkOrderFindTypeEnum._10.getKey()) == vo.getType()) {
            vo.setWorkOrderStatus(Integer.parseInt(WorkOrderStautsEnum._2.getKey()));
            vo.setMaintenanceStatus(Integer.valueOf(MaintainWorkOrderStautsEnum._3.getKey()));
        }
        /*if (!StringUtils.isEmpty(vo.getXzqhdm())) {
            String xzqhdm = vo.getXzqhdm();
            String xzqhJb = tXzqhMapper.getAreaCodeLevel(xzqhdm);
            String subXzqhDigit = XzqhUtils.subXzqhDigit(xzqhJb);
            String xzqhdmLike = vo.getXzqhdm().substring(0, Integer.parseInt(subXzqhDigit));
            vo.setXzqhdm(xzqhdmLike);
        }*/
        vo.setCompanyId(Long.parseLong(vo.getOperateUserCompanyId()));
        vo.setCompanyType(vo.getOperateUserCompanyType());
        List<WorkOrderListExportDto> dtos = this.baseMapper.exportWorkOrderList(vo);
        for (WorkOrderListExportDto dto : dtos) {
            if(dto.getCreateDate() !=null) {
             dto.setFormattedCreateDate(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date(dto.getCreateDate())));
            }
            if (StrUtil.isEmpty(dto.getCreateUserName())) {
                dto.setCreateUserName("移动端用户");
            }
            if (ObjectUtil.equals(dto.getMaintainStatus(), 3) && ObjectUtil.equals(dto.getWorkOrderStateName(), "处理中")) {
                dto.setWorkOrderStateName("未接单");
            }
        }
        return dtos;
    }

    @Override
    public int bindCompany(BindCompanyVo vo) {
        DeleteBindCompanyVo deleteBindCompanyVo = new DeleteBindCompanyVo();
        deleteBindCompanyVo.setPCompanyId(vo.getOperateUserCompanyId());
        deleteBindCompanyVo.setCompanyId(vo.getCompanyId());
        QueryBindCompanyDto queryBindCompanyDto = bindCompanyMapper.queryBindCompanyById(deleteBindCompanyVo);
        if (ObjectUtil.isNotEmpty(queryBindCompanyDto)) {
            BindCompany bindCompany = new BindCompany();
            bindCompany.setId(Long.valueOf(queryBindCompanyDto.getId()));
            bindCompany.setCompanyId(queryBindCompanyDto.getCompanyId());
            bindCompany.setPCompangId(queryBindCompanyDto.getPCompanyId());
            bindCompany.setIsdel(0);
            return bindCompanyMapper.updateById(bindCompany);
        }
        BindCompany bindCompany = new BindCompany();
        bindCompany.setCompanyId(vo.getCompanyId());
        bindCompany.setPCompangId(vo.getOperateUserCompanyId());
        bindCompany.setGmtModified(vo.getOperateDate());
        bindCompany.setGmtCreateId(vo.getOperateUserId());
        bindCompany.setIsdel(0);
        return bindCompanyMapper.insert(bindCompany);
    }


    @Override
    public Page<QueryBindCompanyDto> queryBindCompany(QueryBindCompanyVo vo) throws Exception {
        vo.setPCompanyId(vo.getOperateUserCompanyId());
        vo.setCompanyType("02");
        Page<QueryBindCompanyDto> page = new Page<>(vo.getPageid(), vo.getPagesize());
        List<QueryBindCompanyDto> data = bindCompanyMapper.queryBindCompany(page, vo);
            Company company = businessCompanyService.getCompany(vo.getOperateUserCompanyId());
            QueryBindCompanyDto companyDto=new QueryBindCompanyDto();
            companyDto.setCompanyId(company.getCompanyid());
            companyDto.setCompanyname(company.getCompanyname());
            if(ObjectUtil.isNotEmpty(data)){
                data.add(companyDto);
                return page.setRecords(data);
            }else{
                List<QueryBindCompanyDto> data1 =new ArrayList<>();
                data1.add(companyDto);
                return page.setRecords(data1);
            }

    }

    @Override
    public int unBindCompany(DeleteBindCompanyVo vo) {
        vo.setPCompanyId(vo.getOperateUserCompanyId());
        return bindCompanyMapper.unBindCompany(vo);
    }


    public void updateWorkOrderInfo(Long PWorkOrderId, CompleteOrderRepairVo vo) {
        if (ObjectUtil.isNotEmpty(PWorkOrderId)) {
            WorkOrderInfo workOrder = callWorkOrderInfoService.selectByPrimaryKey(PWorkOrderId);
            workOrder.setMaintainStatus(Integer.valueOf(MaintainWorkOrderStautsEnum._2.getKey()));
            workOrder.setStatus(Integer.valueOf(WorkOrderStautsEnum._6.getKey()));
            callWorkOrderInfoService.updateByPrimaryKey(workOrder);
            //写工单记录，返回工单记录id
            WorkOrderRecord workOrderRecord = new WorkOrderRecord();
            workOrderRecord.setWorkOrderId(PWorkOrderId);
            //如果不是等待配件
            if (vo.getRepairResult() == 0) {
                workOrderRecord.setDesc("维修完成");
                workOrderRecord.setStatus(Integer.parseInt(WorkOrderStautsEnum._6.getKey()));
            } else {
                workOrderRecord.setDesc("等待配件");
                workOrderRecord.setStatus(Integer.parseInt(WorkOrderStautsEnum._2.getKey()));
            }
            workOrderRecord.setIsDelete(Integer.valueOf(DeleteEnum._0.getKey()));
            workOrderRecord.setGmtCreate(vo.getOperateTimeStamp());
            workOrderRecord.setGmtModified(vo.getOperateTimeStamp());
            workOrderRecord.setDesc("故障描述:" + paramParamMapper.getFaultDescById(vo.getFaultType()));
            workOrderRecord.setLongitude(vo.getLongitude());
            workOrderRecord.setLatitude(vo.getLatitude());
            workOrderRecordService.saveWorkOrderRecord(workOrderRecord);
            if (workOrder.getPWorkOrderId() != null) {
                updateWorkOrderInfo(workOrder.getPWorkOrderId(), vo);
            } else {
                updateWorkOrderInfo(null, vo);

            }
        }
    }


    public void updateworkOrderRecord(Long PWorkOrderId, WorkOrderInfo vo, WorkOrderStatusVo workOrderStatusVo) {
        WorkOrderInfo workOrder = null;
        if (ObjectUtil.isNotEmpty(PWorkOrderId)) {
            workOrder = callWorkOrderInfoService.selectByPrimaryKey(PWorkOrderId);
            workOrder.setMaintainStatus(Integer.parseInt(MaintainWorkOrderStautsEnum._3.getKey()));
            workOrder.setStatus(Integer.parseInt(WorkOrderStautsEnum._2.getKey()));
            callWorkOrderInfoService.updateByPrimaryKey(workOrder);
            //写工单记录，返回工单记录id
            WorkOrderRecord workOrderRecord = new WorkOrderRecord();
            workOrderRecord.setWorkOrderId(PWorkOrderId);
            workOrderRecord.setIsDelete(Integer.valueOf(DeleteEnum._0.getKey()));
            workOrderRecord.setGmtCreate(workOrderStatusVo.getOperateTimeStamp());
            workOrderRecord.setGmtModified(workOrderStatusVo.getOperateTimeStamp());
            workOrderRecord.setStatus(Integer.parseInt(WorkOrderStautsEnum._2.getKey()));
            workOrderRecord.setDesc(WorkOrderRecordEnum._1.getVal());
            workOrderRecord.setLongitude(vo.getLongitude());
            workOrderRecord.setLatitude(vo.getLatitude());
            workOrderRecordService.saveWorkOrderRecord(workOrderRecord);
            if (workOrder.getPWorkOrderId() != null) {
                updateworkOrderRecord(workOrder.getPWorkOrderId(), vo, workOrderStatusVo);
            } else {
                updateworkOrderRecord(null, vo, workOrderStatusVo);

            }
        }

    }

    @Override
    public Page<Company> getCommissionAgent(GetCommissionAgentVo vo) {
        QueryCompanyVO queryCompanyVO = new QueryCompanyVO();
        queryCompanyVO.setOperateUserCompanyId(vo.getOperateUserCompanyId());
        queryCompanyVO.setOperateUserCompanyType("02");
        queryCompanyVO.setPageid(vo.getPageid());
        queryCompanyVO.setPagesize(vo.getPagesize());
        queryCompanyVO.setQuery(vo.getCompanyName());
        Page<Company> page = businessCompanyService.getCompanys(queryCompanyVO);
        /*if (ObjectUtil.isNotEmpty(page)) {
            QueryBindCompanyVo queryBindCompanyVo = new QueryBindCompanyVo();
            queryBindCompanyVo.setPCompanyId(vo.getOperateUserCompanyId());
            Page<QueryBindCompanyDto> pages = new Page<>(vo.getPageid(), vo.getPagesize());
            List<QueryBindCompanyDto> data = bindCompanyMapper.queryBindCompany(pages, queryBindCompanyVo);
            if (ObjectUtil.isNull(data)) {
                return page;
            }
            List<Company> pagesData = page.getRecords();
            List<Company> intersection = pagesData.stream()
                    .filter(obj1 -> data.stream().anyMatch(obj2 -> obj2.getCompanyId().equals(obj1.getCompanyid())))
                    .collect(Collectors.toList());
            for (int i = 0; i < intersection.size(); i++) {
                intersection.get(i).setIsBind(true);
            }
            return page;
        }*/
        return page;
    }

    @Override
    public Set<String> getAreaCodeSetByMaintainIds(Set<Long> callCenterUserIdSet) {
        if (CollectionUtil.isEmpty(callCenterUserIdSet)) {
            throw new MissBusinessParameterException("callCenterUserIdSet must not empty");
        }

        QueryWrapper<WorkOrderInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.select("xzqhdm");
//        queryWrapper.eq("status", WorkOrderStautsEnum._2.getKey());
        queryWrapper.eq("is_delete", false);
        queryWrapper.in("maintain_id", callCenterUserIdSet);

        return this.baseMapper.selectList(queryWrapper).stream().map(WorkOrderInfo::getXzqhdm).collect(Collectors.toSet());
    }

    private QueryInstallWorkOrderBO perHandleVO(GetWorkOrderInstallPageVO vo) throws Exception {
        // 准备返回值
        QueryInstallWorkOrderBO queryBO = new QueryInstallWorkOrderBO();

        vo.formatTime();
        vo.setWorkOrderType(Long.valueOf(WorkOrderTypeEnum._4.getKey()));

        // 处理项目相关参数：项目名称、项目类型、项目状态
        if (StrUtil.isNotBlank(vo.getProjectName())
                || StrUtil.isNotBlank(vo.getProjectType())
                || StrUtil.isNotBlank(vo.getProjectStatus())
                || ObjectUtil.isNotNull(vo.getProjectId())) {
            Set<Long> workOrderIdSet = crmFlowTableRelationshipService.getWorkOrderIdSet(vo);
            if (CollectionUtil.isEmpty(workOrderIdSet)) {
                // 如果用项目校验,未匹配到任何工单id,直接返回空
                queryBO.setReturnEmpty(Boolean.TRUE);
                return queryBO;
            }
            queryBO.setWorkOrderIdSet(workOrderIdSet);
        }

        // 处理客服中心id
        Set<String> callCenterCompanyIdSet = businessCompanyService.getCcCompanyIdSet(vo.getOperateUserCompanyType(), vo.getOperateUserCompanyId());
        queryBO.setCallCenterCompanyIdSet(callCenterCompanyIdSet);

        // 处理施工人员id
        if (ObjectUtil.isNotNull(vo.getMaintainId())) {
            TUser maintainUserInfo = systemUserService.getUserInfoByUserId(String.valueOf(vo.getMaintainId()));
            queryBO.setMaintainUserId(maintainUserInfo.getCallCenterUserId());
        }

        // 处理状态参数：是否可撤销
        if (ObjectUtil.isNotNull(vo.getCanCancel()) && StrUtil.isBlank(vo.getWorkOrderState())) {
            if (vo.getCanCancel()) {
                // 查询可撤销的 - 未完成
                queryBO.setStatusList(WorkOrderStautsEnum.getStatusList(false));
            } else {
                // 查询不可撤销的 - 已完成
                queryBO.setStatusList(WorkOrderStautsEnum.getStatusList(true));
            }
        }

        return queryBO;
    }

    private List<GetWorkOrderInstallPageDTO> postHandleResult(List<GetWorkOrderInstallPageDTO> records) throws Exception {
        // 查询项目类别字典
        Map<String, TParam> projectTypeParamMap = tParamService.getMapValueIsKey("92");
        // 取出全部工单id
        Set<Long> workOrderIdSet = records.stream().map(GetWorkOrderInstallPageDTO::getWorkOrderId).collect(Collectors.toSet());
        // 查询工单对应的项目id
        Map<Long, Long> workOrderProjectIdMap = crmFlowTableRelationshipService.getWorkOrderProjectIdMap(workOrderIdSet);
        // 查询工单对应的拒单次数
        Map<Long, Long> rejectionCountMap = workOrderRejectionInfoService.queryRejectionCountMap(workOrderIdSet);

        // 设置返回值
        for (GetWorkOrderInstallPageDTO item : records) {
            item.setWorkOrderStatusName(WorkOrderStautsEnum.getVal(item.getWorkOrderStatus()));
            item.setCanCancel(!WorkOrderStautsEnum.getIsComplete(item.getWorkOrderStatus())); // 取反
            item.setWorkOrderServiceStatusName(WorkOrderServiceStautsEnum.getVal(item.getWorkOrderServiceStatus()));
            item.setWorkTypeName(OrderWorkTypeEnum.getVal(item.getWorkTypeId().intValue()));
            item.setEmergencyDegreeName(WorkOrderEmergencyDegreeEnum.getVal(item.getEmergencyDegreeId()));

            // 处理拒单次数
            item.setRejectionCount(ObjectUtil.isNull(rejectionCountMap.get(item.getWorkOrderId())) ? 0L : rejectionCountMap.get(item.getWorkOrderId()));

            // 处理项目相关字段
            Long projectId = workOrderProjectIdMap.get(item.getWorkOrderId());
            if (ObjectUtil.isNotNull(projectId)) {
                TProject projectDetail = tProjectService.getProjectDetail(projectId);
                if (ObjectUtil.isNotNull(projectDetail)) {
                    item.setProjectId(String.valueOf(projectId));
                    item.setProjectName(projectDetail.getProjectName());
                    item.setProjectType(projectDetail.getProjectType());
                    // 存在项目类别字典，赋值项目类别名称
                    if (!projectTypeParamMap.isEmpty()) {
                        item.setProjectTypeName(projectTypeParamMap.getOrDefault(projectDetail.getProjectType(), new TParam()).getName());
                    }
                }
            }

            // 处理公司相关字段
            Company company = businessCompanyService.getCompanyByCallCenterCompanyId(item.getCallCenterCompanyId());
            if (ObjectUtil.isNotNull(company)) {
                item.setCompanyId(company.getCompanyid());
                item.setCompanyName(company.getCompanyname());
            }

            // 处理派单人相关字段
            TUser createUserInfo = systemUserService.getUserInfoByCallCenterUserId(item.getCcUserId());
            if (ObjectUtil.isNotNull(createUserInfo)) {
                item.setCreateUserId(createUserInfo.getId());
                item.setCreateUserName(createUserInfo.getNickName());
                item.setOrderCreateUserId(createUserInfo.getUuid());
            }

            // 处理接单人相关字段
            TUser maintainUserInfo = systemUserService.getUserInfoByCallCenterUserId(item.getMaintainId());
            if (ObjectUtil.isNotNull(maintainUserInfo)) {
                item.setMaintainName(maintainUserInfo.getNickName());
            }
        }
        return records;
    }

    /**
     * 根据工单id查询处理人id(热链云用户id)
     */
    public Map<Long, String> queryWorkOrderMaintainIdByWorkOrderId(List<Long> workOrderIdList) {
        // 查询所有工单对应的长效管护用户id
        QueryWrapper<WorkOrderInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.select("maintain_id");
        queryWrapper.in("id", workOrderIdList);
        List<WorkOrderInfo> workOrderInfos = this.baseMapper.selectList(queryWrapper);

        if (CollectionUtil.isEmpty(workOrderInfos)) {
            return new HashMap<>();
        }
        // 准备一个map接收返回值
        Map<Long, String> map = new HashMap<>();
        // 准备另一个map接收长效管护和热链云用户id,避免重复查询
        Map<Long, Long> userIdMap = new HashMap<>();
        // 组装返回值
        for (WorkOrderInfo workOrderInfo : workOrderInfos) {
            if (userIdMap.containsKey(workOrderInfo.getMaintainId())) {
                map.put(workOrderInfo.getId(), String.valueOf(userIdMap.get(workOrderInfo.getId())));
                continue;
            }

            TUser userInfo = systemUserService.getUserInfoByCallCenterUserId(String.valueOf(workOrderInfo.getMaintainId()));
            if (ObjectUtil.isNull(userInfo)) {
                log.error("长效管护用户id:{}未同步到热链云!", workOrderInfo.getMaintainId());
                continue;
            }
            userIdMap.put(workOrderInfo.getMaintainId(), userInfo.getId());
            map.put(workOrderInfo.getId(), String.valueOf(userInfo.getId()));
        }
        return map;
    }
}
